How do I get a date in YYYY-MM-DD format?
Asked Answered
I

15

35

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

Interweave answered 24/8, 2015 at 22:45 Comment(6)
I recommend using momentjs.com for all of your javascript date needs, it makes everything much easier.Alwyn
possible duplicate of How to format a JavaScript dateGoodson
In UTC, d.toISOString().split('T')[0]Veritable
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]: #12409799Stonybroke
What about d.toLocaleDateString()? That will give you exactly the result in your first example.Gladdy
I can't believe such a simple request could not be solved by Javascript native function.Gregale
A
91

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.

Ardys answered 24/8, 2015 at 22:53 Comment(2)
This probably needs a note that the result will be in UTC (GMT+0000), not the client's local timezone (such as GMT-0700)Veritable
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.Bevbevan
I
12

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
Insecticide answered 24/8, 2015 at 22:52 Comment(3)
x < 10 is much cheaper than .split and saves you .toStringingVeritable
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.Insecticide
any reason for the .toString()?Athanor
T
11

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'

Thermos answered 1/2, 2023 at 13:57 Comment(2)
the most elegant one I've seenGlia
Looks like you can just use new Date().toLocaleDateString("en-CA") .. you can also specify a timezone to change the date to a local one somewhere else, e.g. new Date().toLocaleDateString("en-CA", { timeZone: "Australia/Sydney"})Eleazar
F
9

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">
Flin answered 4/3, 2018 at 8:41 Comment(0)
R
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");
Regional answered 15/4, 2019 at 12:19 Comment(0)
S
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));
Schweinfurt answered 20/9, 2019 at 8:23 Comment(0)
P
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"));
Pervert answered 28/1, 2018 at 6:21 Comment(2)
Please add explanation. Code only answer isn't really very helpful.Gladdy
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.Dihedron
S
1

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.

Standstill answered 7/2, 2020 at 21:47 Comment(0)
A
1

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;
}
Amourpropre answered 7/3, 2022 at 9:7 Comment(0)
S
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 :)

Stouthearted answered 1/12, 2016 at 6:43 Comment(1)
This is just asking for a problem on DST boundaries (and other, even weirder quirks of certain timezones/locales).Shostakovich
G
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.

Gladdy answered 28/1, 2018 at 8:30 Comment(0)
C
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.

Caravaggio answered 18/7, 2018 at 1:37 Comment(2)
Also is missing the leading zero adding to year, because someone could be using a year that has less than 4 digits.Dihedron
@Dihedron 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...Caravaggio
F
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]
}
Fivespot answered 17/4, 2022 at 17:22 Comment(1)
This won't work consistently unless your timezone is GMT, because toISOString converts from local to UTC time.Tiemroth
E
0

I like this to get timestamps to the second that, when sorted alphanumerically, are in the correct order time-wise:

(new Date().toLocaleString("en-CA", 
    { timeZone: 'America/Los_Angeles', hourCycle: 'h24', 
      year: 'numeric', month: '2-digit', day: '2-digit', 
      hour: '2-digit', minute: '2-digit', second: '2-digit'})).replace(/\D+/g, '-')

// Output: '2023-10-03-09-16-12'

Every field is always the same length. You can change the timezone at will (I use this in my JS client for logging so that the timestamps match up with those in the server logs in Seattle). You can lop off some precision if you want, or even get it down to the millisecond by adding this to the list of options:

fractionalSecondDigits: '3'

Seems like this should be easier, but now that you have this one-liner it is....

Epagoge answered 3/10, 2023 at 17:7 Comment(0)
C
-2

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>
Catamenia answered 19/4, 2022 at 18:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.