This question already has an answer here:
- How to format a JavaScript date 50 answers
$a = date('Y-m-d h:i:s');
echo $a;
result:
2017-08-18 09:14:02
Is there a way to get the date in the same format using javascript / jquery ?
</div>
This question already has an answer here:
$a = date('Y-m-d h:i:s');
echo $a;
result:
2017-08-18 09:14:02
Is there a way to get the date in the same format using javascript / jquery ?
</div>
Here's an approach that is easy to understand for newer JavaScript developers who come from an OOP background.
var date = new Date();
alert(date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)).slice(-2) + "-" + ("0" + date.getDate()).slice(-2) + " " + ("0" + date.getHours()).slice(-2) + ":" + ("0" + date.getMinutes()).slice(-2) + ":" + ("0" + date.getSeconds()).slice(-2));
date.getMonth() + 1
because the months are 0 indexed.
EDIT: The above solution now adds the leading zeros to getMonth()
and getDay()
. The slice(-2)
call is a common way to getting the last two characters from the string.
For example, if date.getMonth()
returns a 9
. I would get 09
, and slice(-2)
would return me the same 09
.
But if date.getMonth()
returns a 10
. I would get 010
, and slice(-2)
would return the last two characters again. So, 10
.
The other answers are correct, this one is just easier to understand from a beginners perspective.