[javascript] How to get year/month/day from a date object?

alert(dateObj) gives Wed Dec 30 2009 00:00:00 GMT+0800

How to get date in format 2009/12/30?

This question is related to javascript date

The answer is


I would suggest you to use Moment.js http://momentjs.com/

Then you can do:

moment(new Date()).format("YYYY/MM/DD");

Note: you don't actualy need to add new Date() if you want the current TimeDate, I only added it as a reference that you can pass a date object to it. for the current TimeDate this also works:

moment().format("YYYY/MM/DD");

info

If a 2 digit month and date is desired (2016/01/01 vs 2016/1/1)

code

var dateObj = new Date();
var month = ('0' + (dateObj.getMonth() + 1)).slice(-2);
var date = ('0' + dateObj.getDate()).slice(-2);
var year = dateObj.getFullYear();
var shortDate = year + '/' + month + '/' + date;
alert(shortDate);

output

2016/10/06

fiddle

https://jsfiddle.net/Hastig/1xuu7z7h/

credit

More info from and credit to this answer

more

To learn more about .slice the try it yourself editor at w3schools helped me understand better how to use it.


ES2018 introduced regex capture groups which you can use to catch day, month and year:

const REGEX = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2});
const results = REGEX.exec('2018-07-12');
console.log(results.groups.year);
console.log(results.groups.month);
console.log(results.groups.day);

Advantage of this approach is possiblity to catch day, month, year for non-standard string date formats.

Ref. https://www.freecodecamp.org/news/es9-javascripts-state-of-art-in-2018-9a350643f29c/


let dateObj = new Date();

let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());

For reference you can see the below details

new Date().getDate()          // Return the day as a number (1-31)
new Date().getDay()           // Return the weekday as a number (0-6)
new Date().getFullYear()      // Return the four digit year (yyyy)
new Date().getHours()         // Return the hour (0-23)
new Date().getMilliseconds()  // Return the milliseconds (0-999)
new Date().getMinutes()       // Return the minutes (0-59)
new Date().getMonth()         // Return the month (0-11)
new Date().getSeconds()       // Return the seconds (0-59)
new Date().getTime()          // Return the time (milliseconds since January 1, 1970)

_x000D_
_x000D_
let dateObj = new Date();_x000D_
_x000D_
let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());_x000D_
_x000D_
console.log(myDate)
_x000D_
_x000D_
_x000D_

// Return the minutes (0-59) new Date().getMonth() // Return the month (0-11) new Date().getSeconds() // Return the seconds (0-59) new Date().getTime() // Return the time (milliseconds since January 1, 1970)


var date = new Date().toLocaleDateString()
"12/30/2009"

Why not using the method toISOString() with slice or simply toLocaleDateString()?

Check here:

_x000D_
_x000D_
const d = new Date() // today, now

console.log(d.toISOString().slice(0, 10)) // YYYY-MM-DD

console.log(d.toLocaleDateString('en-US')) // M/D/YYYY
console.log(d.toLocaleDateString('de-DE')) // D.M.YYYY
console.log(d.toLocaleDateString('pt-PT')) // DD/MM/YYYY
_x000D_
_x000D_
_x000D_


2021 ANSWER

You can use the native .toLocaleDateString() function which supports several useful params like locale (to select a format like MM/DD/YYYY or YYYY/MM/DD), timezone (to convert the date) and formats details options (eg: 1 vs 01 vs January).

Examples

new Date().toLocaleDateString() // 8/19/2020

new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // 08/19/2020 (month and day with two digits)

new Date().toLocaleDateString('en-ZA'); // 2020/08/19 (year/month/day) notice the different locale

new Date().toLocaleDateString('en-CA'); // 2020-08-19 (year-month-day) notice the different locale

new Date().toLocaleString("en-US", {timeZone: "America/New_York"}); // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)

new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"});  // 09 (just the hour)

Notice that sometimes to output a date in your specific desire format, you have to find a compatible locale with that format. You can find the locale examples here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all

Please notice that locale just change the format, if you want to transform a specific date to a specific country or city time equivalent then you need to use the timezone param.


new Date().toISOString()
"2016-02-18T23:59:48.039Z"
new Date().toISOString().split('T')[0];
"2016-02-18"
new Date().toISOString().replace('-', '/').split('T')[0].replace('-', '/');
"2016/02/18"

new Date().toLocaleString().split(',')[0]
"2/18/2016"

With the accepted answer, January 1st would be displayed like this: 2017/1/1.

If you prefer 2017/01/01, you can use:

var dt = new Date();
var date = dt.getFullYear() + '/' + (((dt.getMonth() + 1) < 10) ? '0' : '') + (dt.getMonth() + 1) + '/' + ((dt.getDate() < 10) ? '0' : '') + dt.getDate();

Here is a cleaner way getting Year/Month/Day with template literals:

_x000D_
_x000D_
var date = new Date();_x000D_
var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`;_x000D_
console.log(formattedDate);
_x000D_
_x000D_
_x000D_


Use the Date get methods.

http://www.tizag.com/javascriptT/javascriptdate.php

http://www.htmlgoodies.com/beyond/javascript/article.php/3470841

var dateobj= new Date() ;
var month = dateobj.getMonth() + 1;
var day = dateobj.getDate() ;
var year = dateobj.getFullYear();

EUROPE (ENGLISH/SPANISH) FORMAT
I you need to get the current day too, you can use this one.

function getFormattedDate(today) 
{
    var week = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
    var day  = week[today.getDay()];
    var dd   = today.getDate();
    var mm   = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
    var hour = today.getHours();
    var minu = today.getMinutes();

    if(dd<10)  { dd='0'+dd } 
    if(mm<10)  { mm='0'+mm } 
    if(minu<10){ minu='0'+minu } 

    return day+' - '+dd+'/'+mm+'/'+yyyy+' '+hour+':'+minu;
}

var date = new Date();
var text = getFormattedDate(date);


*For Spanish format, just translate the WEEK variable.

var week = new Array('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado');


Output: Monday - 16/11/2015 14:24


var dt = new Date();

dt.getFullYear() + "/" + (dt.getMonth() + 1) + "/" + dt.getDate();

Since month index are 0 based you have to increment it by 1.

Edit

For a complete list of date object functions see

Date

getMonth()

Returns the month (0-11) in the specified date according to local time.

getUTCMonth()

Returns the month (0-11) in the specified date according to universal time.


Nice formatting add-in: http://blog.stevenlevithan.com/archives/date-time-format.

With that you could write:

var now = new Date();
now.format("yyyy/mm/dd");

You can simply use This one line code to get date in year-month-date format

var date = new Date().getFullYear() + "-" + new Date().getMonth() + 1 + "-" + new Date().getDate();

I am using this which works if you pass it a date obj or js timestamp:

getHumanReadableDate: function(date) {
    if (date instanceof Date) {
         return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
    } else if (isFinite(date)) {//timestamp
        var d = new Date();
        d.setTime(date);
        return this.getHumanReadableDate(d);
    }
}