Get String in YYYYMMDD format from JS date object?

Ask a question
8

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

Coin iconoffer bounty
add comment

3 Answers

8

You can do in this way:

Date.prototype.yyyymmdd = function() { 
    var mm = this.getMonth() + 1; 
    var dd = this.getDate(); 
    return [
            this.getFullYear(), 
            (mm>9 ? '' : '0') + mm, 
            (dd>9 ? '' : '0') + dd 
    ].join(''); 
}; 
var date = new Date(); date.yyyymmdd();
add comment
7

An alternative to the prototype would be:

var justNow = new Date(); 
var myRes = justNow.toISOString().slice(0,10).replace(/-/g,""); 
document.body.innerHTML += myRes;
add comment
5

I do it like this

new Date('Jun 5 2016')
    .toLocaleString('en-us', {year: 'numeric', month: '2-digit', day: '2-digit'})
    .replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');
add comment

Your Answer