0

I am trying to convert a timestamp from d/m/yyyy to yyyy-mm-dd through JavaScript. Here is my code.

        var d = new Date();
        d.setDate(d.getDate()-5);
        temp = d.toLocaleString({minimumIntegerDigits: 2, useGrouping:false}).split(',')[0].split("/").reverse().join("-");
        console.log(temp)

I am getting output like this 2016-5-5, but what I am suppose to get is 2016-05-05. I tried options like minimumIntegerDigits with toLocaleString but its not working.

Thanks in advance.

StepUp
  • 36,391
  • 15
  • 88
  • 148
Rajesh
  • 75
  • 1
  • 4
  • 14
  • 2
    This has got to be the hundredth question about converting dates using JS. Please next time, use google. – evolutionxbox May 10 '16 at 09:42
  • You're not really trying to convert *from* a particular format, you just want to get a date object as a string in the yyyy-mm-dd format. I wouldn't use `toLocaleString()` options, because not all browsers support that. – nnnnnn May 10 '16 at 09:43

2 Answers2

0

try this

d.toLocaleString().split(',')[0].split("/").map( function(val, index, arr){ 
   if (index < arr.length - 1) 
   { 
     return ("0" + val).slice(-2); 
   } 
   return val;
}).reverse().join("-");

DEMO

var d = new Date();
d.setDate(d.getDate() - 5);

var output = d.toLocaleString().split(',')[0].split("/").map(function(val, index, arr) {
  if (index < arr.length - 1) {
    return ("0" + val).slice(-2);
  }
  return val;
}).reverse().join("-");

alert( output )
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

Use this

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

d = new Date();
d.yyyymmdd();

Related to this answer Get String in YYYYMMDD format from JS date object?

Community
  • 1
  • 1