0

Apologies if duplicate

I have a date in Mon May 29 2017 12:36:49 GMT+0000 and I want to convert it into 2017-05-01T19:04:18Z How can i do that using JavaScript.

Here is my code

var targetDate = new Date();
 targetDate.setDate(targetDate.getDate() - 5);
 console.log("targetDate is "+targetDate); 

I am getting output like targetDate is Mon May 29 2017 12:36:49 GMT+0000 but I want it in 2017-05-01T19:04:18Z format

Any help appreciated, Thanks in advance

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Nyki
  • 97
  • 1
  • 9
  • Have a look at .toLocaleString and other methods of the Date.prototype – Jonas Wilms Jun 03 '17 at 12:50
  • Possible duplicate of [Javascript Date output formatting](https://stackoverflow.com/questions/8362952/javascript-date-output-formatting). Just to make it clear: **JS only outputs dates in full string format**. Next time google. – kabanus Jun 03 '17 at 12:50
  • 1
    There are [*many similar questions*](https://stackoverflow.com/search?q=%5Bjavascript%5D+change+date+format), the simplest solution is to parse to a Date and use [*toISOString*](http://ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.toisostring). For parsing, see [*fecha.js*](https://github.com/taylorhakes/fecha) or [*moment.js*](https://momentjs.com). – RobG Jun 03 '17 at 12:58
  • Glad to see some attention finally being paid to date formatting! SO needs more questions on this topic. By the way, what is the rule for transforming May 29th into May 1st? –  Jun 03 '17 at 13:30
  • Take care to correctly spell JavaScript to avoid search collision with Java. – Basil Bourque Jun 03 '17 at 15:00

3 Answers3

0

This is not the best practice, but still putting it here for your reference:

Date.prototype.toString = function() {
    return `${this.getFullYear()}-${this.getMonth() + 1}-${this.getDate()}T${this.getHours()}:${this.getMinutes()}:${this.getSeconds()}`;
}

d = new Date()
2017-6-3T18:39:34
bugs_cena
  • 495
  • 5
  • 11
0
function addZero(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}

var targetDate = new Date(); 
targetDate.setDate(targetDate.getDate() - 5);
var newTime = targetDate.getFullYear()+"-"+addZero(targetDate.getMonth())+"-"+addZero(targetDate.getDate())+" "+addZero(targetDate.getHours())+":"+addZero(targetDate.getMinutes())+":"+addZero(targetDate.getSeconds());
alert(newTime);
Chandrika Shah
  • 638
  • 6
  • 6
0

Are you looking for JSON encoded date?

You can parse that with the JSON serializer:

console.log("targetDate is "+ JSON.stringify(targetDate));
Secko
  • 7,664
  • 5
  • 31
  • 37