Advertisement
Advertisement


Get String in YYYYMMDD format from JS date object?


Question

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

2020/08/24
1
413
8/24/2020 9:26:40 PM

Accepted Answer

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();
2016/11/24
631
11/24/2016 11:03:07 AM


You can use the toISOString function :

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

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

2019/09/16

Moment.js could be your friend

var date = new Date();
var formattedDate = moment(date).format('YYYYMMDD');
2017/06/13

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

2013/12/18

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);
2016/03/16

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'
2016/06/06

Source: https://stackoverflow.com/questions/3066586
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]