Getting year, month and day with JS


I want to get today’s date with JavaScript in this format: YYYY-MM-DD

Example: 2017-06-12

In PHP, I can get it with the following simple line:

$today = date('Y-m-d');

In JavaScript, I use the following:

var today = new Date();

var day = today.getDate();
if (day < 10) day = '0'+day;
var month = today.getMonth();
if (month < 10) month = '0'+month;
var year = today.getFullYear();**

var todayDate = year+'-'+month+'-'+day;

Is there no simpler way for this like how PHP handles it?

today.toISOString().substr(0, 10)

(although that uses the UTC timezone)

1 Like

Thanks for the tip. Good to know it, regardless of it uses UTC.

for more comfortable working with dates, check out

1 Like

Thanks for the link, though, I prefer to keep my code as simple as possible, unless I absolutely need to use an external script.

In JavaScript there is no inbuilt date function do show a date in a given format so you have to manually do some coding like what you have shown in the question itself.

There are many developers that have created a data format solution.

See for example,

even I but as i said it is not given in javascript by default.

Yes, that is correct, which is why you can supply it yourself.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.