28

Normally if I wanted to get the date I could just do something like

var d = new Date(); console.log(d);

The problem with doing that, is when I run that code, it returns:

Mon Aug 24 2015 4:20:00 GMT-0800 (Pacific Standard Time)

How could I get the Date() method to return a value in a "MM-DD-YYYY" format so it would return something like:

8/24/2015

Or, maybe MM-DD-YYYY H:M

8/24/2016 4:20

6
  • 3
    I recommend using momentjs.com for all of your javascript date needs, it makes everything much easier.
    – house9
    Aug 24, 2015 at 22:47
  • 2
    possible duplicate of How to format a JavaScript date Aug 24, 2015 at 22:47
  • 6
    In UTC, d.toISOString().split('T')[0]
    – Paul S.
    Aug 24, 2015 at 22:47
  • I think you can find your answer here:- [How to get current formatted date dd/mm/yyyy in Javascript and append it to an input. ][1] [1]: stackoverflow.com/questions/12409299/… Aug 24, 2015 at 22:59
  • 1
    I can't believe such a simple request could not be solved by Javascript native function.
    – Zhang Buzz
    Oct 9, 2018 at 10:08

14 Answers 14

86

Just use the built-in .toISOString() method like so: toISOString().split('T')[0]. Simple, clean and all in a single line.

var date = (new Date()).toISOString().split('T')[0];
document.getElementById('date').innerHTML = date;
<div id="date"></div>

Please note that the timezone of the formatted string is UTC rather than local time.

2
  • 14
    This probably needs a note that the result will be in UTC (GMT+0000), not the client's local timezone (such as GMT-0700)
    – Paul S.
    Aug 24, 2015 at 22:56
  • 2
    Warning! Since this method converts the date to UTC, the resulting string will stubbornly be plus or minus a day depending on your timezone and the time of day. So it's annoyingly not the best solution.
    – JakeMc
    Apr 28, 2022 at 1:23
13

The below code is a way of doing it. If you have a date, pass it to the convertDate() function and it will return a string in the YYYY-MM-DD format:

var todaysDate = new Date();

function convertDate(date) {
  var yyyy = date.getFullYear().toString();
  var mm = (date.getMonth()+1).toString();
  var dd  = date.getDate().toString();

  var mmChars = mm.split('');
  var ddChars = dd.split('');

  return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}

console.log(convertDate(todaysDate)); // Returns: 2015-08-25
2
  • 3
    x < 10 is much cheaper than .split and saves you .toStringing
    – Paul S.
    Aug 24, 2015 at 22:55
  • Yes because the Month starts at 0. January = 0, February is 1. You want it like January = 1, February = 2, so we add 1 to the value.
    – Starfish
    Aug 25, 2015 at 6:44
8

Yet another way:

var today = new Date().getFullYear()+'-'+("0"+(new Date().getMonth()+1)).slice(-2)+'-'+("0"+new Date().getDate()).slice(-2)
document.getElementById("today").innerHTML = today
<div id="today">

5

By using Moment.js library, you can do:

var datetime = new Date("2015-09-17 15:00:00");
datetime = moment(datetime).format("YYYY-MM-DD");
4

One line solution for 'YYYY-MM-DD'

new Date().toLocaleDateString("fr-CA", {year:"numeric", month: "2-digit", day:"2-digit"})

// output on New Years Eve 2023: '2023-12-31'

1
  • the most elegant one I've seen
    – mWang
    Mar 15 at 2:14
2
var today = new Date();

function formatDate(date) {
 var dd = date.getDate();
        var mm = date.getMonth() + 1; //January is 0!
        var yyyy = date.getFullYear();
        if (dd < 10) {
          dd = '0' + dd;
        }
        if (mm < 10) {
          mm = '0' + mm;
        }
        //return dd + '/' + mm + '/' + yyyy;
             return yyyy + '/' + mm + '/' +dd ;

}

console.log(formatDate(today));
1
function formatdate(userDate){
  var omar= new Date(userDate);
  y  = omar.getFullYear().toString();
  m = omar.getMonth().toString();
  d = omar.getDate().toString();
  omar=y+m+d;
  return omar;
}
console.log(formatDate("12/31/2014"));
2
  • 2
    Please add explanation. Code only answer isn't really very helpful.
    – cezar
    Jan 28, 2018 at 8:11
  • This code does not work and has two issues: It will not produce the yyyy-mm-dd format because you're not adding leading zeroes to years, months nor dates. test it when your date is "0001-01-01". Your month will always be decreased by 1 because Date.getMonth() returns 0 for January. Oct 15, 2020 at 15:21
0

If you are trying to get the 'local-ISO' date string. Try the code below.

function (date) {
    return new Date(+date - date.getTimezoneOffset() * 60 * 1000).toISOString().split(/[TZ]/).slice(0, 2).join(' ');
}

+date Get milliseconds from a date.

Ref: Date.prototype.getTimezoneOffset Have fun with it :)

1
  • This is just asking for a problem on DST boundaries (and other, even weirder quirks of certain timezones/locales).
    – Ry-
    Jan 8, 2018 at 12:11
0

What you want to achieve can be accomplished with native JavaScript. The object Date has methods that generate exactly the output you wish.
Here are code examples:

var d = new Date();
console.log(d);
>>> Sun Jan 28 2018 08:28:04 GMT+0000 (GMT)
console.log(d.toLocaleDateString());
>>> 1/28/2018
console.log(d.toLocaleString());
>>> 1/28/2018, 8:28:04 AM

There is really no need to reinvent the wheel.

0

Here is a simple function I created when once I kept working on a project where I constantly needed to get today, yesterday, and tomorrow's date in this format.

function returnYYYYMMDD(numFromToday = 0){
  let d = new Date();
  d.setDate(d.getDate() + numFromToday);
  const month = d.getMonth() < 9 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1;
  const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
  return `${d.getFullYear()}-${month}-${day}`;
}

console.log(returnYYYYMMDD(-1)); // returns yesterday
console.log(returnYYYYMMDD()); // returns today
console.log(returnYYYYMMDD(1)); // returns tomorrow

Can easily be modified to pass it a date instead, but here you pass a number and it will return that many days from today.

2
  • Also is missing the leading zero adding to year, because someone could be using a year that has less than 4 digits. Oct 15, 2020 at 15:23
  • 1
    @ErroneousFatality good point, but as I prefaced in my answer this is an example how I grabbed the date for today/tomorrow/yesterday/etc. So unless OP is a time traveler...
    – Lou Bagel
    Oct 15, 2020 at 15:44
0

If you're not opposed to adding a small library, Date-Mirror (NPM or unpkg) allows you to format an existing date in YYYY-MM-DD into whatever date string format you'd like.

date('n/j/Y', '2020-02-07') // 2/7/2020
date('n/j/Y g:iA', '2020-02-07 4:45PM') // 2/7/2020 4:45PM
date('n/j [until] n/j', '2020-02-07', '2020-02-08') // 2/7 until 2/8

Disclaimer: I developed Date-Mirror.

0
0

This will convert a unix timestamp to local date (+ time)

function UnixTimeToLocalDate = function( unix_epoch_time )
{
    var date,
        str;
        
    date = new Date( unix_epoch_time * 1000 );
    
    str = date.getFullYear() + '-' +
          (date.getMonth() + 1 + '').padStart( 2, '0' )  + '-' +
          (date.getDate() + '').padStart( 2, '0' );

    // If you need hh:mm:ss too then

    str += ' ' +
          (date.getHours()   + '').padStart( 2, '0' ) + ':' +
          (date.getMinutes() + '').padStart( 2, '0' ) + ':' +
          (date.getSeconds() + '').padStart( 2, '0' );
          
    return str;
}
0

If you want a text format that's good for sorting use:

function formatDateYYYYMMDDHHMMSS(date){
  // YYYY-MM-DD HH:MM:SS
  const datePart = date.toISOString().split("T")[0]
  const timePart = date.toLocaleString('en-US', {hour12: false}).split(",")[1]
  return datePart + timePart
}

As prototype:

Date.prototype.toSortString = function(){
  const date = new Date(this.valueOf());
  return date.toISOString().split("T")[0] + 
         date.toLocaleString('en-US', {hour12: false}).split(",")[1]
}
1
  • This won't work consistently unless your timezone is GMT, because toISOString converts from local to UTC time.
    – Auspex
    Nov 4, 2022 at 13:21
-1

const padTo2Digits = num => {
  return num.toString().padStart(2, '0')
}

const formatDate = date => {
  return [
    date.getFullYear(),
    padTo2Digits(date.getMonth() + 1),
    padTo2Digits(date.getDate())
  ].join('-')
}

let value = formatDate(new Date())

document.getElementById('dayFormatUS').innerHTML = value

const transformDate = date => {
  const convert = date.split('-').reverse()
  return convert.join('/')
}

document.getElementById('dayFormatBR').innerHTML = transformDate(value)
<div>
  Format US - 
  <span id='dayFormatUS'></span>
</div>

<div>
  Format BR - 
  <span id='dayFormatBR'></span>
</div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.