how can I add the current date and time with this format: 2022-07-17 17:50:20
?
I already managed it with an input value but I need the current time.
Advertisement
Answer
You should use built-in Date object in Javascript, like this:
JavaScript
x
9
1
let currentdate = new Date();
2
let datetime = currentdate.getFullYear() + "-"
3
+ String((currentdate.getMonth() + 1)).padStart(2,"0") + "-"
4
+ String(currentdate.getDate()).padStart(2,"0") + " "
5
+ String(currentdate.getHours()).padStart(2,"0") + ":"
6
+ String(currentdate.getMinutes()).padStart(2,"0") + ":"
7
+ String(currentdate.getSeconds()).padStart(2,"0");
8
//The `+1` on the getMonth() is used because in Javascript January is 0.
9
console.log(datetime);
By the way, I suggest you make all your var
s into let
s as that’s the current standard. There’s a very fine difference between them (let is block scoped while var is functional scoped).