382

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

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

user198729
  • 61,774
  • 108
  • 250
  • 348

20 Answers20

582
let dateObj = new Date();
let month = dateObj.getUTCMonth() + 1; //months from 1-12
let day = dateObj.getUTCDate();
let year = dateObj.getUTCFullYear();

newdate = year + "/" + month + "/" + day;

or you can set new date and give the above values

BlizZ
  • 15
  • 8
Hiyasat
  • 8,601
  • 7
  • 33
  • 59
  • 84
    Just remember: January=0, February=1, and so on. – Rubens Farias Jan 06 '10 at 13:53
  • 16
    What's the difference between `getMonth` and `getUTCMonth`? – user198729 Jan 06 '10 at 13:54
  • 15
    UTC will return universal time. if you want local time use getMonth – Hiyasat Jan 06 '10 at 13:56
  • 66
    `getUTCDay()` should be replaced by `getUTCDate()`, since day is the number of the day in week (0-6) and date is the number of the day in month (1-31). – Grzegorz Oledzki Jan 12 '10 at 08:36
  • 4
    This response is still flawed I believe. getUTCDate() will return the Day of the month indeed but in England. For example if I type: var d = new Date("July 21, 1983 01:15:00"); d.getDate() returns 21 but d.getUTCDate() returns only 20 This is because at 01:15 in the morning in France (where I am), it is still 23:15 in England. To get the day that was in the original Date you should use getDate(). – Pascal Ganaye Oct 10 '16 at 21:49
  • 1
    @PascalGanaye Regardless whether the response is flawed or not (strictly taken considering the question it actually is), what you say is not only true for the day. It applies also for month and year (consider e.g. "Jan 1, 1983 01:15:00"). – jox Aug 18 '18 at 23:32
  • year,month and day should be padded with 0 like newdate = [year, month, day].map((num) => `0${num}`.slice(-2) ).join("/"); – Viraj Singh Mar 03 '21 at 17:58
  • "getUTCDate()" should be replaced by (getUTCDate() + 1) or getDate() – Emrah Tuncel Aug 13 '21 at 15:36
193
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"
davidcondrey
  • 34,416
  • 17
  • 114
  • 136
  • 4
    I think this could be better for third case new Date().toISOString().split('T')[0].replace(/-/g, '/'); – Mohamed Hesham Apr 25 '18 at 22:27
  • using `replaceAll`instead of `replace` would make more sense. Example: `new Date().toISOString().split('T')[0].replaceAll('-', '/')` – pycvalade Apr 27 '23 at 18:39
118
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.

Josh Burgess
  • 9,327
  • 33
  • 46
rahul
  • 184,426
  • 49
  • 232
  • 263
63

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

Beware that the timezone returned by toISOString is always zero UTC offset, whereas in toLocaleDateString it is the user agent's timezone.

Check here:

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

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

// Timezone of User Agent
console.log(d.toLocaleDateString('en-CA')) // 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
João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
  • 1
    For anyone whose getting back dates from Mongo & need them in `year/month/day` this is your answer ^^^. Example: `new Date("2021-01-01T00:00:00.000Z").toISOString().slice(0,10) ` – Clifford Fajardo Jan 14 '21 at 01:26
  • great answer! maybe someday there'll be a `.toISODateString()` that does this. – keithpjolley Feb 08 '21 at 20:16
  • This gives me a wrong date, `new Date(1618264800000).toLocaleDateString()` => "13.4.2021", but `new Date(1618264800000).toISOString().slice(0, 10)` => "2021-04-12". So it's one day diff. – dude Apr 12 '21 at 15:54
  • 1
    : @dude it depends on the UTC or locale time, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date – João Pimentel Ferreira Apr 12 '21 at 19:26
36

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");
fmsf
  • 36,317
  • 49
  • 147
  • 195
  • 3
    This answer is good if you wish to add a dependency - and if so as of 2019 day.js is a lighter weight alternative to moment.js as an option to consider - https://github.com/iamkun/dayjs. Also mentioned there is Luxon and date-fns. – BradGreens Sep 10 '19 at 17:02
36

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.

Juanma Menendez
  • 17,253
  • 7
  • 59
  • 56
22
var date = new Date().toLocaleDateString()
"12/30/2009"
aldokkani
  • 853
  • 1
  • 8
  • 17
22
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)

let dateObj = new Date();

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

console.log(myDate)
Srikrushna
  • 4,366
  • 2
  • 39
  • 46
  • The UTC versions of these methods get you the year, month, etc. in UTC. Mixing them with the non-UTC versions will get you nonsensical output (unless you're currently on GMT, in which case you won't notice, but your users will). – ksenzee Mar 12 '23 at 05:56
21

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.

Hastig Zusammenstellen
  • 4,286
  • 3
  • 32
  • 45
18

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();
A G
  • 21,087
  • 11
  • 87
  • 112
15

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");
miku
  • 181,842
  • 47
  • 306
  • 310
9

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

Philip Enc
  • 1,072
  • 15
  • 21
7

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();
Basj
  • 41,386
  • 99
  • 383
  • 673
2

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

var date = new Date();
var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`;
console.log(formattedDate);
Exil
  • 311
  • 2
  • 11
  • 26
2

It's Dynamic It will collect the language from user's browser setting

Use minutes and hour property in the option object to work with them.. You can use long value to represent month like Augest 23 etc...

function getDate(){
 const now = new Date()
 const option = {
  day: 'numeric',
  month: 'numeric',
  year: 'numeric'
 }
 const local = navigator.language
 labelDate.textContent = `${new 
 Intl.DateTimeFormat(local,option).format(now)}`
}
getDate()
2

One liner, using destructuring.

Makes 3 variables of type string:

const [year, month, day] = (new Date()).toISOString(). substring(0, 10).split('-')

Makes 3 variables of type number (integer):

const [year, month, day] = (new Date()).toISOString(). substring(0, 10).split('-').map(x => parseInt(x, 10))

From then, it's easy to combine them any way you like:

const [year, month, day] = (new Date()).toISOString(). substring(0, 10).split('-');
const dateFormatted = `${year}/${month}/${day}`;
Vadorequest
  • 16,593
  • 24
  • 118
  • 215
  • 1
    Great answer! Works for me! It may be better to use substring(), as substr() is marked as deprecated on the Mozilla developers website. `This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards ... Be aware that this feature may cease to work at any time.` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr – Dazza Apr 30 '23 at 12:06
  • Good point, updated. – Vadorequest Apr 30 '23 at 20:52
1

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();
Muhammad Ahsan
  • 249
  • 4
  • 13
1

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/

SL5net
  • 2,282
  • 4
  • 28
  • 44
Przemek Struciński
  • 4,990
  • 1
  • 28
  • 20
  • The question was specifically asking about formatting a date in "month/day/year" from a Date object. Capture groups in regex are not applicable here. – Colin Dec 06 '19 at 14:39
0
let currentYear = date.getFullYear() ;
let currentMonth = date.getMonth() + 1 ; // 0 - 11
let currentDay = date.getDate() ; 
  
//The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length.
// 0-9 it will pad 0 at beginning
// 10 - 31 it will not pad     
const addPad = (num) => {
   return num.toString().padStart(2,'0')
}

console.log(addPad(10)) // 10 
console.log(addPad(1)) // 01  0-9 it will pad 0 at begining


let dateWithSlash = [ addPad(currentDay) , addPad(currentMonth) ,  currentYear].join("/")  // 01/01/2023
let dateWithHyphen = [ addPad(currentDay) , addPad(currentMonth) ,  currentYear].join("-") // 01-01-2023
Avnish Jayaswal
  • 161
  • 1
  • 4
-1

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);
    }
}
alex toader
  • 2,300
  • 1
  • 17
  • 20