538

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()?

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
IVR Avenger
  • 15,090
  • 13
  • 46
  • 57
  • 7
    Concatenating those three is the way to go – Juan Cortés Jun 18 '10 at 00: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' – kennebec Jun 18 '10 at 04:33

53 Answers53

708

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();
mb21
  • 34,845
  • 8
  • 116
  • 142
o-o
  • 8,158
  • 2
  • 20
  • 21
  • 18
    You should replace `[1]` with `.length===2`, because an indexer on a string is not fully supported. [See this answer for reasons why.](http://stackoverflow.com/a/5943760/613176) – Aidiakapi Mar 04 '14 at 17:22
  • 8
    var mm = (this.getMonth() + 101).toStrung().substring(0, 2); – 9dan Aug 20 '15 at 09:17
  • 9
    For anyone wanting a practical example of @Aidiakapi 's fix, I create a fiddle here: https://jsfiddle.net/pcr8xbt5/1/ – killercowuk Aug 24 '16 at 18:55
  • 2
    If you want to have dots separator: `[this.getFullYear(), mm<10 ? '0'+ mm: mm, dd<10 ? '0'+ dd : dd].join('.')` – Kamil Kiełczewski Sep 28 '16 at 12:15
  • 5
    @9dan shouldn't it be `var mm = (this.getMonth() + 101).toString().substring(1, 3)` – Pnar Sbi Wer Nov 08 '16 at 09:56
  • 1
    @o-o according with w3 school, you only should modify your own prototypes. Never modify the prototypes of standard JavaScript objects like `Date` – Yago Azedias Mar 16 '18 at 18:35
  • `[]` is pretty safe, nobody is modifying the string character here, and it's only not supported on very old browsers, such as IE7-. – Andre Figueiredo Oct 02 '18 at 19:04
  • 1
    For people who are really beginners in JS/programming. You can adapt join('') to `join('-')` to get your yyyy-mm-dd format. Just saying. – Melroy van den Berg Sep 26 '19 at 23:31
  • Yet another hack ... I dont undestant the upvotes on this thing. *facepalm* – fonZ May 05 '20 at 09:28
  • Check [my answer](https://stackoverflow.com/a/27038188/883603) for a less hacky, more timezone friendly approach. – Dormouse Feb 24 '22 at 20:53
391

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

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

<!-- Next line is for code snippet output only -->
document.body.innerHTML += res;
cssyphus
  • 37,875
  • 18
  • 96
  • 111
Pierre Guilbert
  • 5,057
  • 3
  • 19
  • 19
  • 65
    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,"")` – BigBlueHat Sep 26 '13 at 17:43
  • 9
    I wanted `YYYYMMDDHHmmSSsss`, so I did this: `var ds = (new Date()).toISOString().replace(/[^0-9]/g, "");`. Pretty simple, but should be encapsulated. – Jess Oct 11 '13 at 13:06
  • 86
    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' – weberste Dec 12 '13 at 10:23
  • 1
    I ended up using momentjs afterall ;) – Pierre Guilbert Feb 25 '14 at 11:45
  • @digiguru could use a polyfill like json2 http://stackoverflow.com/questions/11440569/converting-a-normal-date-to-iso-8601-format – Pierre Guilbert Jan 30 '15 at 09:54
  • 36
    This would fail if someone in the year 10000 would use your 'nostalgic' code. – Trevi Awater Jul 13 '15 at 22:34
  • 2
    @Aʟᴀɢᴀʀᴏs in that case, `(new Date).toISOString().split('T')[0].replace(/-/g,"");`? – Cameron Tangney Aug 20 '15 at 07:07
  • 12
    A suggested improvement to cope with timezones. `rightNow.setMinutes(rightNow.getMinutes() - rightNow.getTimezoneOffset()); rightNow.toISOString().slice(0,10)` – Andreas Dec 29 '15 at 15:20
  • 2
    As @weberste pointed out, depending on your timezone, this might not work as you expect. So I'll strongly recommend to use the selected answer from o-o . – xarlymg89 Mar 02 '16 at 14:24
  • I agree with @xarlymg89; I downvoted because this solution would not work if the user's timezone is *ahead* of UTC, right? For example, [most of Europe](https://upload.wikimedia.org/wikipedia/commons/8/88/World_Time_Zones_Map.png) is GMT + 1 as @weberste explains. – Nate Anderson Jan 13 '20 at 02:18
  • @BigBlueHat You don't have to wrap `new Date()` with brackets, `new`'s execution order is earlier than other operators like `.` and `()` – Lying_cat Nov 12 '21 at 03:07
249

You can use the toISOString function :

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

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

bjb568
  • 11,089
  • 11
  • 50
  • 71
Ramzi SAYAGH
  • 2,595
  • 1
  • 10
  • 3
  • 42
    In some cases this will not include the right day, because of timezone daylight etc... – Miguel Jun 22 '15 at 11:09
  • 4
    Maybe my creativity is broken @Miguel, but I can't think of a case where that would happen. Would you mind providing an example? – cloudworks Aug 05 '15 at 21:22
  • 47
    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. – Luke Baulch Sep 13 '15 at 02:44
  • A bit shorter... var today = (new Date()).toISOString().substring(0, 10); – teawithfruit Jul 13 '16 at 15:41
  • 1
    Fails with different GMT – Tobia Mar 19 '20 at 09:07
  • 6
    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. – Erdal G. Jul 17 '20 at 08:01
  • The timezones will ruin it, I am in +3 GMT and I get the date, but it is 3 hours behind –  Aug 29 '21 at 09:51
  • Check [my answer](https://stackoverflow.com/a/27038188/883603) for a more timezone friendly approach. – Dormouse Feb 24 '22 at 20:52
  • Timezone issue can be fixed with getTimezoneOffset() method: `(date=>new Date(date.valueOf()-60*1000*date.getTimezoneOffset()).toISOString().substring(0, 10))(new Date())` – lexa-b Oct 17 '22 at 12:06
174

Moment.js could be your friend

var date = new Date();
var formattedDate = moment(date).format('YYYYMMDD');
disco crazy
  • 31,313
  • 12
  • 80
  • 83
53
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'
gongqj
  • 762
  • 6
  • 14
  • 9
    Best soultion . – Sos. Jun 09 '18 at 02:12
  • 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');` – nenea Apr 01 '19 at 12:23
40

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

NLemay
  • 2,331
  • 3
  • 29
  • 45
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);
Brian Powell
  • 3,336
  • 4
  • 34
  • 60
33

I don't like modifying native objects, and I think multiplication is clearer than the string padding 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/

M.A.K. Ripon
  • 2,070
  • 3
  • 29
  • 47
Darren Griffith
  • 3,290
  • 3
  • 28
  • 35
  • 4
    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. – Darren Griffith Feb 20 '15 at 18:52
  • 4
    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! – A. Masson Aug 25 '15 at 15:47
  • 1
    Thanks for this answer I created the fiddle here https://jsfiddle.net/amwebexpert/L6j0omb4/ – A. Masson Aug 25 '15 at 16:00
  • 1
    I did not need the multiplication at all and I don't understand why it is there. http://jsfiddle.net/navyjax2/gbqmv0t5/ Otherwise, leave that out, and this is a great answer and helped me a lot. – vapcguy Nov 17 '15 at 21:32
  • @vapcguy : The multiplication is there to avoid string concatenation. It shifts the year and month to the left. Your solution works as well, but it concatenates strings. I haven't run tests, but it is likely slower. – Darren Griffith Nov 17 '15 at 22:29
  • 1
    @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! – vapcguy Nov 17 '15 at 23:54
  • Definitely the best answer. – FrenkyB May 20 '20 at 11:43
  • Answer would be perfect if (as of 2020) `var` would be replaced by `let` as it's function scoped here – Erdal G. Jul 17 '20 at 07:59
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.

alfredo-fredo
  • 652
  • 7
  • 7
27

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>
M.A.K. Ripon
  • 2,070
  • 3
  • 29
  • 47
Eric Herlitz
  • 25,354
  • 27
  • 113
  • 157
  • If someone likes to use that, I suggest DRY here, reuse the already created functions instead of doing the same all over again. – RiZKiT Jan 23 '17 at 10:48
  • @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 – Eric Herlitz Jan 23 '17 at 11:34
  • 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. – le hollandais volant Dec 26 '18 at 14:48
24

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.

Dormouse
  • 1,617
  • 1
  • 23
  • 33
  • now.getMonth() will return 0 for January, it should be (now.getMonth() + 1) – Jas Apr 12 '15 at 15:05
  • 2
    Wrong. Date's UTC function expects month to be between 0 and 11 (but other < 0 and > 11 is allowed). – Dormouse Apr 13 '15 at 12:59
  • Why do you replace multiple hyphens by a single one? Can `toISOString` return multiple successive hyphens? – Michaël Witrant Oct 19 '16 at 17:14
  • 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 – Gerard ONeill Dec 21 '16 at 17:40
  • Changed the replace with hyphen to empty char, to match OP's question. – Dormouse Mar 10 '17 at 15:06
  • 2
    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! – Guillaume F. May 12 '17 at 13:12
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
Kus
  • 2,529
  • 27
  • 27
  • 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) – tomwoods May 26 '16 at 13:22
  • thx, to get YYYY-MM-DD i used: new Date(Date.now()-(new Date()).getTimezoneOffset() * 60000).toISOString().slice(0, 10).replace(/[^0-9]/g, "-") – Nick Humphrey Sep 06 '16 at 15:16
  • @Kus how can i get milliseconds well? – O'Dane Brissett Oct 08 '20 at 18:36
12

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.

trincot
  • 317,000
  • 35
  • 244
  • 286
10

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

console.log(dateFormated);
Tomas Šivickas
  • 977
  • 9
  • 10
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');

Milkncookiez
  • 6,817
  • 10
  • 57
  • 96
7

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())
Tamir Nakar
  • 933
  • 1
  • 10
  • 17
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.

Tom Tom
  • 3,680
  • 5
  • 35
  • 40
6

Shortest

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

let d = new Date();

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

console.log(s);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
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.

Strelok
  • 50,229
  • 9
  • 102
  • 115
5

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;
}
Community
  • 1
  • 1
Hero Qu
  • 911
  • 9
  • 10
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();
garyh
  • 2,782
  • 1
  • 26
  • 28
Muhammad Ahsan
  • 249
  • 4
  • 13
5

How about Day.js?

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

https://github.com/iamkun/dayjs

NoobTW
  • 2,466
  • 2
  • 24
  • 42
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('-');
};
juliv
  • 51
  • 1
  • 3
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,'')
Chawathe Vipul S
  • 1,636
  • 15
  • 28
  • This was super close for me, but the order of `DateTimeFormat` was different. I suspect it is localized. – Connor Clark Jul 15 '20 at 22:58
  • 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 – Erdal G. Jul 17 '20 at 07:55
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,"")
anmml
  • 253
  • 3
  • 8
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);
Manohar Reddy Poreddy
  • 25,399
  • 9
  • 157
  • 140
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.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Oren_H
  • 4,481
  • 2
  • 17
  • 8
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"
Ogglas
  • 62,132
  • 37
  • 328
  • 418
3

From ES6 onwards you can use template strings to make it a little shorter:

var now = new Date();
var todayString = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()}`;

This solution does not zero pad. Look to the other good answers to see how to do that.

MyrionSC2
  • 1,248
  • 1
  • 14
  • 24
  • 5
    There are two bugs in your code: 1) you don't account for the fact that `getMonth()` is zero-based and 2) you don't pad with zeros. In sum, "Jan 1, 2020" will result in `2020-0-1` which is far from ideal. – Daniel Liuzzi Apr 28 '20 at 17:05
  • Many many techniques for zero padding has been shown in the other answers, I really just wanted to show the template strings. But I will add a disclaimer to the answer. – MyrionSC2 May 05 '20 at 11:32
2

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}")
andersh
  • 8,105
  • 6
  • 39
  • 30
2

If using AngularJs (up to 1.5) you can use the date filter:

var formattedDate = $filter('date')(myDate, 'yyyyMMdd')
sarin
  • 5,227
  • 3
  • 34
  • 63
  • So, in order to format one variable, he needs to refactoring the whole application from whatever to AngularJS? – Sang Dang Jun 05 '21 at 06:49
  • @SangDang The OP mentions Javascript in the question. All answers are giving different Javascript possibilities. Javascript based frameworks are one possible answer. – sarin Oct 04 '21 at 08:03
2

yyyymmdd=x=>(f=x=>(x<10&&'0')+x,x.getFullYear()+f(x.getMonth()+1)+f(x.getDate()));
alert(yyyymmdd(new Date));
Enam
  • 29
  • 1
  • 1
    adding some description to your answer will get you upvotes try to describe a bit what you are doing in this code so others can understand it more clearly. – Muhammad Omer Aslam Jan 13 '18 at 22:11
  • In strict mode or typescript use "let f,yyyymmdd=x=>..." instead. Functions yyyymmdd and f are otherwise undefined. – maxeh May 24 '18 at 15:44
2

date-shortcode to the rescue!

const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYYMMDD}', new Date())
//=> '20180304'
Kodie Grantham
  • 1,963
  • 2
  • 17
  • 27
2

A lot of answers here use the toisostring function. This function converts the time to zulu time before outputting, which may cause issues.

function datestring(time) {
    return new Date(time.getTime() - time.getTimezoneOffset()*60000).toISOString().slice(0,10).replace(/-/g,"")
}

mydate = new Date("2018-05-03")
console.log(datestring(mydate))

The datestring function fixes the timezone issue, or even better you can avoid the whole issue by working in zulu time:

mydate = new Date("2018-05-03Z")
// mydate = new Date(Date.UTC(2018,5,3))
console.log(mydate.toISOString().slice(0,10).replace(/-/g,""))
Kristian K
  • 491
  • 5
  • 11
2
const date = new Date()

console.log(date.toISOString().split('T')[0]) // 2022-12-27
Gaurav
  • 857
  • 3
  • 21
  • 29
1

Here is a more generic approach which allows both date and time components and is identically sortable as either number or string.

Based on the number order of Date ISO format, convert to a local timezone and remove non-digits. i.e.:

// monkey patch version
Date.prototype.IsoNum = function (n) {
    var tzoffset = this.getTimezoneOffset() * 60000; //offset in milliseconds
    var localISOTime = (new Date(this - tzoffset)).toISOString().slice(0,-1);
    return localISOTime.replace(/[-T:\.Z]/g, '').substring(0,n || 20); // YYYYMMDD
}

Usage

var d = new Date();
// Tue Jul 28 2015 15:02:53 GMT+0200 (W. Europe Daylight Time)
console.log(d.IsoNum(8));  // "20150728"
console.log(d.IsoNum(12)); // "201507281502"
console.log(d.IsoNum());   // "20150728150253272"
chriskelly
  • 7,526
  • 3
  • 32
  • 50
1

Native Javascript:

new Date().toLocaleString('zu-ZA').slice(0,10).replace(/-/g,'');
Lonnie Best
  • 9,936
  • 10
  • 57
  • 97
1

Sure, you can build a specific function for each variation of date string representations. If you consider international date formats you wind up with dozens of specific functions with rediculous names and hard to distinguish.

There is no reasonable function that matches all formats, but there is a reasonable function composition that does:

const pipe2 = f => g => x =>
  g(f(x));

const pipe3 = f => g => h => x =>
  h(g(f(x)));

const invoke = (method, ...args) => o =>
  o[method] (...args);

const padl = (c, n) => s =>
  c.repeat(n)
    .concat(s)
    .slice(-n);

const inc = n => n + 1;

// generic format date function

const formatDate = stor => (...args) => date =>
  args.map(f => f(date))
    .join(stor);

// MAIN

const toYYYYMMDD = formatDate("") (
  invoke("getFullYear"),
  pipe3(invoke("getMonth")) (inc) (padl("0", 2)),
  pipe2(invoke("getDate")) (padl("0", 2)));

console.log(toYYYYMMDD(new Date()));

Yes, this is a lot of code. But you can express literally every string date representation by simply changing the function arguments passed to the higher order function formatDate. Everything is explicit and declarative i.e., you can almost read what's happening.

1

One Liner (2022) w/ Correct Timezone Offset

var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 10).replaceAll("-", "");

// YearMonthDay

var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 10).replaceAll("-", "");

console.log("YearMonthDay");
console.log(dateDisplay);

// Year-Month-Day

var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 10);

console.log("Year-Month-Day");
console.log(dateDisplay);

// Year-Month-Day Hour:Minute:Second

var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 19).replace("T", " ");

console.log("Year-Month-Day Hour:Minute:Second");
console.log(dateDisplay);

// Year-Month-Day Hour-Minute-Second

var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 19).replace("T", " ").replaceAll(":", "-");

console.log("Year-Month-Day Hour-Minute-Second");
console.log(dateDisplay);

// ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ

var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON();

console.log("ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ");
console.log(dateDisplay);
theMaxx
  • 3,756
  • 2
  • 27
  • 33
1

I've written a simple function, which can convert a Date object to String with date number, month number (with zero padding) and year number in customizable order. You can use it with any separator you like or leave this parameter empty to have no separator in output. Please, have a look.

function dateToString(date, $1, $2, $3, separator='') {
  const dateObj = {
    date: String(date.getDate()).padStart(2, '0'),
    month: String(date.getMonth() + 1).padStart(2, '0'),
    year: date.getFullYear()
  };

  return dateObj[$1] + separator + dateObj[$2] + separator + dateObj[$3];
}

const date = new Date();

const dateString1 = dateToString(date, 'year', 'month', 'date');
console.log(dateString1);

// Manipulate arguments order to get output you want
const dateString2 = dateToString(date, 'date', 'month', 'year', '-');
console.log(dateString2);
0

Here is a little improvement to the answer from https://stackoverflow.com/users/318563/o-o

Date.prototype.ddmmyyyy = function(delimiter) {
    var yyyy = this.getFullYear().toString();
    var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
    var dd  = this.getDate().toString();
    return (dd[1]?dd:"0"+dd[0]) + delimiter + (mm[1]?mm:"0"+mm[0]) + delimiter +yyyy  ; // padding
};

Hope to be helpfull for anyone!

:)

bachonk
  • 3,924
  • 1
  • 14
  • 14
Ismael Terreno
  • 1,021
  • 8
  • 5
0
Try this:

function showdate(){

var a = new Date();
var b = a.getFullYear();
var c = a.getMonth();
(++c < 10)? c = "0" + c : c;
var d = a.getDate();
(d < 10)? d = "0" + d : d;
var final = b + "-" + c + "-" + d; 

return final;


} 

document.getElementById("todays_date").innerHTML = showdate();
0

this post helped me to write this helper, so I share it in case some one is looking for this solution, it supports all variations of yyyy, mm, dd

Date.prototype.formattedDate = function (pattern) {
    formattedDate = pattern.replace('yyyy', this.getFullYear().toString());
    var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
    mm = mm.length > 1 ? mm : '0' + mm;
    formattedDate = formattedDate.replace('mm', mm);
    var dd = this.getDate().toString();
    dd = dd.length > 1 ? dd : '0' + dd;
    formattedDate = formattedDate.replace('dd', dd);
    return formattedDate;
};

d = new Date();
pattern = 'yyyymmdd';  // 20150813
d.formattedDate(pattern);

pattern = 'yyyy-mm-dd';
d.formattedDate(pattern); // 2015-08-13
talsibony
  • 8,448
  • 6
  • 47
  • 46
0

Date.js has a lot of helpful date parsing methods.

require("datejs")

(new Date()).toString("yyyyMMdd")

Tan Wang
  • 811
  • 1
  • 6
  • 16
0

I try to write a simple library for manipulating JavaScript date object. You can try this.

var dateString = timeSolver.getString(date, "YYYYMMDD")

Libarary here: https://github.com/sean1093/timeSolver

sean1093
  • 109
  • 1
  • 3
0

Nice, and easy:

    var date = new Date();
    var yyyy = date.getFullYear();
    var mm = date.getMonth() + 1; // getMonth() is zero-based
    if (mm < 10) mm='0'+mm;
    var dd = date.getDate();
    if (dd < 10) dd='0'+dd;
    /*date.yyyymmdd();*/

    console.log('test - '+yyyy+'-'+mm+'-'+dd);
0

The @o-o solution doesn't work in my case. My solution is the following:

Date.prototype.yyyymmdd = function() {
  var mm = this.getMonth() + 1; // getMonth() is zero-based
  var dd = this.getDate();
  var ret = [this.getFullYear(), (mm<10)?'0':'', mm, (dd<10)?'0':'', dd].join('');

  return ret; // padding
};
fiorentinoing
  • 948
  • 12
  • 20
0

To get the local date, in a YYYYMMDD format, im using:

var todayDate = (new Date()).toLocaleString('en-GB').slice(0,10).split("\/").reverse().join("");
Boaz Saragossi
  • 958
  • 10
  • 32
0

You can create yourself function as below

function toString(o, regex) {
    try {
        if (!o) return '';
        if (typeof o.getMonth === 'function' && !!regex) {
            let splitChar = regex.indexOf('/') > -1 ? '/' : regex.indexOf('-') > -1 ? '-' : regex.indexOf('.') > -1 ? '.' : '';
            let dateSeparate = regex.split(splitChar);
            let result = '';
            for (let item of dateSeparate) {
                let val = '';
                switch (item) {
                    case 'd':
                        val = o.getDate();
                        break;
                    case 'dd':
                        val = this.date2Char(o.getDate());
                        break;
                    case 'M':
                        val = o.getMonth() + 1;
                        break;
                    case 'MM':
                        val = this.date2Char(o.getMonth() + 1);
                        break;
                    case 'yyyy':
                        val = o.getFullYear();
                        break;
                    case 'yy':
                        val = this.date2Char(o.getFullYear());
                        break;
                    default:
                        break;
                }
                result += val + splitChar;
            }
            return result.substring(0, result.length - 1);
        } else {
            return o.toString();
        }
    } catch(ex) { return ''; }
}

function concatDateToString(args) {
    if (!args.length) return '';
    let result = '';
    for (let i = 1; i < args.length; i++) {
        result += args[i] + args[0];
    }
    return result.substring(0, result.length - 1);
}

function date2Char(d){
    return this.rightString('0' + d);
}

function rightString(o) {
    return o.substr(o.length - 2);
}

Used:

var a = new Date();
console.log('dd/MM/yyyy: ' + toString(a, 'dd/MM/yyyy'));
console.log('MM/dd/yyyy: ' + toString(a, 'MM/dd/yyyy'));
console.log('dd/MM/yy: ' + toString(a, 'dd/MM/yy'));
console.log('MM/dd/yy: ' + toString(a, 'MM/dd/yy'));
Trung
  • 1,819
  • 1
  • 13
  • 10
0

I hope this function will be useful

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

    }
-1

Here's a compact little function that's easy to read and avoids local variables, which can be time-sinks in JavaScript. I don't use prototypes to alter standard modules, because it pollutes the namespace and can lead to code that doesn't do what you think it should.

The main function has a stupid name, but it gets the idea across.

function dateToYYYYMMDDhhmmss(date) {
    function pad(num) {
        num = num + '';
        return num.length < 2 ? '0' + num : num;
    }
    return date.getFullYear() + '/' +
        pad(date.getMonth() + 1) + '/' +
        pad(date.getDate()) + ' ' +
        pad(date.getHours()) + ':' +
        pad(date.getMinutes()) + ':' +
        pad(date.getSeconds());
}
-1
var dateDisplay = new Date( 2016-11-09 05:27:00 UTC );
dateDisplay = dateDisplay.toString()
var arr = (dateDisplay.split(' '))
var date_String =  arr[0]+','+arr[1]+' '+arr[2]+' '+arr[3]+','+arr[4]

this will show string like Wed,Nov 09 2016,10:57:00

Michał
  • 2,456
  • 4
  • 26
  • 33
siddhant sankhe
  • 623
  • 6
  • 12
-1
<pre>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]));
    var ampm = (hh >= 12) ? "PM" : "AM";
    format = format.replace(/ampm/g, (ampm[1]?ampm:"0"+ampm[0]));
    return format;
};
var time_var = $('#899_TIME');
var myVar = setInterval(myTimer, 1000);
function myTimer() {
    var d = new Date(); 
    var date = d.getFromFormat('dd-mm-yyyy hh:ii:ss:ampm');
    time_var.text(date);

} </pre>

use the code and get the output like **26-07-2017 12:29:34:PM**

check the below link for your reference

https://parthiban037.wordpress.com/2017/07/26/date-and-time-format-in-oracle-apex-using-javascript/ 
  • Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written – WhatsThePoint Jul 26 '17 at 07:25