557

I'm trying to use JS to turn a date object into a string in YYYYMMDD format. Is there an easier way than concatenating Date.getYear(), Date.getMonth(), and Date.getDay()?

2
  • 7
    Concatenating those three is the way to go Commented Jun 18, 2010 at 0:58
  • 7
    if you want a string that will parse to the same date, don't forget to increment the month. To match your spec you also need to pad single digits in the month and date with '0' Commented Jun 18, 2010 at 4:33

53 Answers 53

717

Altered piece of code I often use:

Date.prototype.yyyymmdd = function() {
  var mm = this.getMonth() + 1; // getMonth() is zero-based
  var dd = this.getDate();

  return [this.getFullYear(),
          (mm>9 ? '' : '0') + mm,
          (dd>9 ? '' : '0') + dd
         ].join('');
};

var date = new Date();
date.yyyymmdd();
Sign up to request clarification or add additional context in comments.

10 Comments

You should replace [1] with .length===2, because an indexer on a string is not fully supported. See this answer for reasons why.
var mm = (this.getMonth() + 101).toStrung().substring(0, 2);
For anyone wanting a practical example of @Aidiakapi 's fix, I create a fiddle here: jsfiddle.net/pcr8xbt5/1
If you want to have dots separator: [this.getFullYear(), mm<10 ? '0'+ mm: mm, dd<10 ? '0'+ dd : dd].join('.')
@9dan shouldn't it be var mm = (this.getMonth() + 101).toString().substring(1, 3)
|
398

I didn't like adding to the prototype. An alternative would be:

const rightNow = new Date();
const res = rightNow.toISOString().slice(0,10).replace(/-/g,"");

// Next line is for code snippet output only
document.body.innerHTML += res;

11 Comments

If you won't need the rightNow variable around, you can wrap new Date and get it all back in a single line: (new Date()).toISOString().slice(0,10).replace(/-/g,"")
I wanted YYYYMMDDHHmmSSsss, so I did this: var ds = (new Date()).toISOString().replace(/[^0-9]/g, "");. Pretty simple, but should be encapsulated.
This won't work in general as Date.toISOString() creates a UTC formatted date and hence can jump date boundaries depending on the timezone. E.g. in GMT+1: (new Date(2013,13, 25)).toISOString() == '2013-12-24T23:00:00.000Z'
This would fail if someone in the year 10000 would use your 'nostalgic' code.
A suggested improvement to cope with timezones. rightNow.setMinutes(rightNow.getMinutes() - rightNow.getTimezoneOffset()); rightNow.toISOString().slice(0,10)
|
261

You can use the toISOString function :

var today = new Date();
today.toISOString().substring(0, 10);

It will give you a "yyyy-mm-dd" format.

9 Comments

In some cases this will not include the right day, because of timezone daylight etc...
Maybe my creativity is broken @Miguel, but I can't think of a case where that would happen. Would you mind providing an example?
If you are in a +1 timezone, and have a date [2015-09-01 00:00:00 GMT+1], then the toISOString() method will return the string '2015-08-31T23:00:00.000Z' because the date is converted to UTC/0-offset before being stringified.
Fails with different GMT
DO NOT USE THIS. I felt for it once, as you may be near to UTC, it's going to work often and fail one in a while.
|
181

Moment.js could be your friend

var date = new Date();
var formattedDate = moment(date).format('YYYYMMDD');

7 Comments

Well it DID add 40kb (minified, non gZip) to my app.js, but I went for it, thanks :).
best answer so far !
I don't even bother waiting until I inevitably need moment anymore, I just add it at the start of a project :)
You can make it easier: var formattedDate = moment().format('YYYYMMDD');
There is an alternative in date-fns which has a smaller footprint (19.5KB vs 71.9KB gzipped).
|
55
new Date('Jun 5 2016').
  toLocaleString('en-us', {year: 'numeric', month: '2-digit', day: '2-digit'}).
  replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');

// => '2016-06-05'

2 Comments

Best soultion .
For some reason, needed to add time (even if 00:00) for the conversion to not skip a day back, when I run the formula here, east coast USA. Once I did that, it started working reliably. What I love about this is it can take the input date in multiple formats, so I don't have to worry about that anymore. new Date('Sun Mar 31 2019 00:00:00.000').toLocaleString('en-us', {year: 'numeric', month: '2-digit', day: '2-digit'}).replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');
42

If you don't need a pure JS solution, you can use jQuery UI to do the job like this :

$.datepicker.formatDate('yymmdd', new Date());

I usually don't like to import too much libraries. But jQuery UI is so useful, you will probably use it somewhere else in your project.

Visit http://api.jqueryui.com/datepicker/ for more examples

Comments

40

This is a single line of code that you can use to create a YYYY-MM-DD string of today's date.

var d = new Date().toISOString().slice(0,10);

3 Comments

^this! FTW! +1.. need to test a bit though.
Warning tough, if your date was 2016-01-01 00:00:00 GMT +2, it will return 2015-12-31 because toISOString() will give 2015-12-31T22:00:00 GMT +0 (two hours before).
See my answer to work around the timezone issue.
39

I don't like modifying native objects, and I think multiplication is clearer than the string padding in the accepted solution.

function yyyymmdd(dateIn) {
  var yyyy = dateIn.getFullYear();
  var mm = dateIn.getMonth() + 1; // getMonth() is zero-based
  var dd = dateIn.getDate();
  return String(10000 * yyyy + 100 * mm + dd); // Leading zeros for mm and dd
}

var today = new Date();
console.log(yyyymmdd(today));

Fiddle: http://jsfiddle.net/gbdarren/Ew7Y4/

8 Comments

This answer was downvoted, and I don't know why. I felt math is faster and clearer than string manipulation. If anyone knows why this is a bad answer, please let me know.
The 10000 multiplicator is there to shift left the YYYY by 4 places (month and day digits needs 2 digits each) and has nothing to do with the Y10K bug. I like this answer and it deserve respect!
Thanks for this answer I created the fiddle here jsfiddle.net/amwebexpert/L6j0omb4
I did not need the multiplication at all and I don't understand why it is there. jsfiddle.net/navyjax2/gbqmv0t5 Otherwise, leave that out, and this is a great answer and helped me a lot.
@D-Money Ah, I figured out what you mean - you're doing a concatenation of a different sort by adding the numbers together to avoid them doing a different math operation on each other - an operation to disallow the normal one that would've otherwise messed them up. Good job! Mine works because I'm using separators (which I'd have to do a .replace('-', '') on to make it answer the OP's question), whereas you were true to the OP's original question and it would not require that extra step. Excellent!
|
31

Local time:

var date = new Date();
date = date.toJSON().slice(0, 10);

UTC time:

var date = new Date().toISOString();
date = date.substring(0, 10);

date will print 2020-06-15 today as i write this.

toISOString() method returns the date with the ISO standard which is YYYY-MM-DDTHH:mm:ss.sssZ

The code takes the first 10 characters that we need for a YYYY-MM-DD format.

If you want format without '-' use:

var date = new Date();
date = date.toJSON().slice(0, 10).split`-`.join``;

In .join`` you can add space, dots or whatever you'd like.

4 Comments

WRONG. As .toISOString(); will return UTC time. So depending on the time and your timezone, the final date you will get can be +1 or -1 day
Edited. You are right. Using ' var date = new Date(); date = date.toJSON().slice(0, 10); ' Gives local time.
Does not give local time.
Check my answer for a solution that does take the localized time into account.
28

In addition to o-o's answer I'd like to recommend separating logic operations from the return and put them as ternaries in the variables instead.

Also, use concat() to ensure safe concatenation of variables

Date.prototype.yyyymmdd = function() {
  var yyyy = this.getFullYear();
  var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based
  var dd = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
  return "".concat(yyyy).concat(mm).concat(dd);
};

Date.prototype.yyyymmddhhmm = function() {
  var yyyymmdd = this.yyyymmdd();
  var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours();
  var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes();
  return "".concat(yyyymmdd).concat(hh).concat(min);
};

Date.prototype.yyyymmddhhmmss = function() {
  var yyyymmddhhmm = this.yyyymmddhhmm();
  var ss = this.getSeconds() < 10 ? "0" + this.getSeconds() : this.getSeconds();
  return "".concat(yyyymmddhhmm).concat(ss);
};

var d = new Date();
document.getElementById("a").innerHTML = d.yyyymmdd();
document.getElementById("b").innerHTML = d.yyyymmddhhmm();
document.getElementById("c").innerHTML = d.yyyymmddhhmmss();
<div>
  yyyymmdd: <span id="a"></span>
</div>
<div>
  yyyymmddhhmm: <span id="b"></span>
</div>
<div>
  yyyymmddhhmmss: <span id="c"></span>
</div>

3 Comments

If someone likes to use that, I suggest DRY here, reuse the already created functions instead of doing the same all over again.
@RiZKiT DRY is a principle and not a pattern but sure, this can be improved a lot. If I where to use this myself I'd probably use another pattern and move the methods away from the prototype. I mainly wrote the example to show there where other ways to solve the problem. Where people take it from there is up to themselves
Nice! I use ("00" + (this.getDate())).slice(-2) to get the numbers two-digits based. There is no "if" or "?:" statement, and less calls to the .getX() function. If not a little bit faster, it’s at least more readable.
25

Plain JS (ES5) solution without any possible date jump issues caused by Date.toISOString() printing in UTC:

var now = new Date();
var todayUTC = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
return todayUTC.toISOString().slice(0, 10).replace(/-/g, '');

This in response to @weberste's comment on @Pierre Guilbert's answer.

6 Comments

now.getMonth() will return 0 for January, it should be (now.getMonth() + 1)
Wrong. Date's UTC function expects month to be between 0 and 11 (but other < 0 and > 11 is allowed).
Why do you replace multiple hyphens by a single one? Can toISOString return multiple successive hyphens?
Michael -- he is replacing each hyphen found with a single hyphen. Still don't know why (perhaps the replacement string is just a place holder for a separator). The 'g' means all occurrences. The pattern you are thinking of is /[-]+/g
You made my day. I've been searching for days for a simple way to bypass the horrible TimeZone handling in Javascript, and this does the trick!
|
13

Another way is to use toLocaleDateString with a locale that has a big-endian date format standard, such as Sweden, Lithuania, Hungary, South Korea, ...:

date.toLocaleDateString('se')

To remove the delimiters (-) is just a matter of replacing the non-digits:

console.log( new Date().toLocaleDateString('se').replace(/\D/g, '') );

This does not have the potential error you can get with UTC date formats: the UTC date may be one day off compared to the date in the local time zone.

Comments

12

// UTC/GMT 0
document.write('UTC/GMT 0: ' + (new Date()).toISOString().slice(0, 19).replace(/[^0-9]/g, "")); // 20150812013509

// Client local time
document.write('<br/>Local time: ' + (new Date(Date.now()-(new Date()).getTimezoneOffset() * 60000)).toISOString().slice(0, 19).replace(/[^0-9]/g, "")); // 20150812113509

3 Comments

This is the answer I used. One liner that takes into account the time zone. To answer the original poster's question, we could do: (new Date(Date.now()-(new Date()).getTimezoneOffset() * 60000)).toISOString().replace(/[^0-9]/g, "").slice(0,8)
thx, to get YYYY-MM-DD i used: new Date(Date.now()-(new Date()).getTimezoneOffset() * 60000).toISOString().slice(0, 10).replace(/[^0-9]/g, "-")
@Kus how can i get milliseconds well?
10

var someDate = new Date();
var dateFormated = someDate.toISOString().substr(0,10);

console.log(dateFormated);

3 Comments

Won't work since new Date() has a timezone and Date.toISOString() is UTC. See my answer.
@Dormouse isn't it the other way around? new Date() creates a new date object which is just a wrapper around nr. of ms since 1970/01/01 00:00:00.000 UTC. Then toISOString prints out in local timezone.
Nope, Date.toISOString() prints in UTC.
8

dateformat is a very used package.

How to use:

Download and install dateformat from NPM. Require it in your module:

const dateFormat = require('dateformat');

and then just format your stuff:

const myYYYYmmddDate = dateformat(new Date(), 'yyyy-mm-dd');

Comments

8

A little variation for the accepted answer:

function getDate_yyyymmdd() {

    const date = new Date();

    const yyyy = date.getFullYear();
    const mm = String(date.getMonth() + 1).padStart(2,'0');
    const dd = String(date.getDate()).padStart(2,'0');

    return `${yyyy}${mm}${dd}`
}

console.log(getDate_yyyymmdd())

Comments

6

Little bit simplified version for the most popular answer in this thread https://stackoverflow.com/a/3067896/5437379 :

function toYYYYMMDD(d) {
    var yyyy = d.getFullYear().toString();
    var mm = (d.getMonth() + 101).toString().slice(-2);
    var dd = (d.getDate() + 100).toString().slice(-2);
    return yyyy + mm + dd;
}

Comments

6

Shortest

.toJSON().slice(0,10).split`-`.join``;

let d = new Date();

let s = d.toJSON().slice(0,10).split`-`.join``;

console.log(s);

Comments

6

Working from @o-o's answer this will give you back the string of the date according to a format string. You can easily add a 2 digit year regex for the year & milliseconds and the such if you need them.

Date.prototype.getFromFormat = function(format) {
    var yyyy = this.getFullYear().toString();
    format = format.replace(/yyyy/g, yyyy)
    var mm = (this.getMonth()+1).toString(); 
    format = format.replace(/mm/g, (mm[1]?mm:"0"+mm[0]));
    var dd  = this.getDate().toString();
    format = format.replace(/dd/g, (dd[1]?dd:"0"+dd[0]));
    var hh = this.getHours().toString();
    format = format.replace(/hh/g, (hh[1]?hh:"0"+hh[0]));
    var ii = this.getMinutes().toString();
    format = format.replace(/ii/g, (ii[1]?ii:"0"+ii[0]));
    var ss  = this.getSeconds().toString();
    format = format.replace(/ss/g, (ss[1]?ss:"0"+ss[0]));
    return format;
};

d = new Date();
var date = d.getFromFormat('yyyy-mm-dd hh:ii:ss');
alert(date);

I don't know how efficient that is however, especially perf wise because it uses a lot of regex. It could probably use some work I do not master pure js.

NB: I've kept the predefined class definition but you might wanna put that in a function or a custom class as per best practices.

Comments

5

This guy here => http://blog.stevenlevithan.com/archives/date-time-format wrote a format() function for the Javascript's Date object, so it can be used with familiar literal formats.

If you need full featured Date formatting in your app's Javascript, use it. Otherwise if what you want to do is a one off, then concatenating getYear(), getMonth(), getDay() is probably easiest.

Comments

5

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

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

Comments

5

Use padStart:

Date.prototype.yyyymmdd = function() {
    return [
        this.getFullYear(),
        (this.getMonth()+1).toString().padStart(2, '0'), // getMonth() is zero-based
        this.getDate().toString().padStart(2, '0')
    ].join('-');
};

Comments

5
[day,,month,,year]= Intl.DateTimeFormat(undefined, { year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(new Date()),year.value+month.value+day.value

or

new Date().toJSON().slice(0,10).replace(/\/|-/g,'')

2 Comments

This was super close for me, but the order of DateTimeFormat was different. I suspect it is localized.
Second line is wrong. As .toISOString(); will return UTC time. So depending on the time and your timezone, the final date you will get can be +1 or -1 day
5
const date = new Date()

console.log(date.toISOString().split('T')[0]) // 2022-12-27

Comments

4

This code is fix to Pierre Guilbert's answer:

(it works even after 10000 years)

YYYYMMDD=new Date().toISOString().slice(0,new Date().toISOString().indexOf("T")).replace(/-/g,"")

Comments

4

Answering another for Simplicity & readability.
Also, editing existing predefined class members with new methods is not encouraged:

function getDateInYYYYMMDD() {
    let currentDate = new Date();

    // year
    let yyyy = '' + currentDate.getFullYear();

    // month
    let mm = ('0' + (currentDate.getMonth() + 1));  // prepend 0 // +1 is because Jan is 0
    mm = mm.substr(mm.length - 2);                  // take last 2 chars

    // day
    let dd = ('0' + currentDate.getDate());         // prepend 0
    dd = dd.substr(dd.length - 2);                  // take last 2 chars

    return yyyy + "" + mm + "" + dd;
}

var currentDateYYYYMMDD = getDateInYYYYMMDD();
console.log('currentDateYYYYMMDD: ' + currentDateYYYYMMDD);

Comments

4

How about Day.js?

It's only 2KB, and you can also dayjs().format('YYYY-MM-DD').

https://github.com/iamkun/dayjs

Comments

3

If you don't mind including an additional (but small) library, Sugar.js provides lots of nice functionality for working with dates in JavaScript. To format a date, use the format function:

new Date().format("{yyyy}{MM}{dd}")

Comments

3

I usually use the code below when I need to do this.

var date = new Date($.now());
var dateString = (date.getFullYear() + '-'
    + ('0' + (date.getMonth() + 1)).slice(-2)
    + '-' + ('0' + (date.getDate())).slice(-2));
console.log(dateString); //Will print "2015-09-18" when this comment was written

To explain, .slice(-2) gives us the last two characters of the string.

So no matter what, we can add "0" to the day or month, and just ask for the last two since those are always the two we want.

So if the MyDate.getMonth() returns 9, it will be:

("0" + "9") // Giving us "09"

so adding .slice(-2) on that gives us the last two characters which is:

("0" + "9").slice(-2)

"09"

But if date.getMonth() returns 10, it will be:

("0" + "10") // Giving us "010"

so adding .slice(-2) gives us the last two characters, or:

("0" + "10").slice(-2)

"10"

Comments

3

It seems that mootools provides Date().format(): https://mootools.net/more/docs/1.6.0/Types/Date

I'm not sure if it worth including just for this particular task though.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.