0

Currently I am making a rest call to SharePoint using JavaScript Rest API. I am getting a Modified date which comes in the following format "2016-08-27T17:40:09Z", from what I have been reading this is a problem many developers have a problem with.

So I decided to go ahead and use the Date.parse(dateString) method to convert the quirky date format and now I am getting Sat Aug 27 2016 13:40:09 GMT-0400 (Eastern Daylight Time).

Now this is something that can be understood, however I am not looking for this, I am looking for the following format Month\Date\Year Hour:Minute. I have been reading the documentation but I am not found anything yet.

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
EasyE
  • 560
  • 5
  • 26
  • 1
    Use [moment.js](http://momentjs.com/) – Syam Pillai Aug 30 '16 at 14:45
  • This question seems to be asked fairly regular: https://stackoverflow.com/questions/8362952/javascript-date-output-formatting https://stackoverflow.com/questions/3066586/get-string-in-yyyymmdd-format-from-js-date-object – daniel f. Aug 30 '16 at 14:47
  • Using back slashes for the date separator is unusual, more common is forward slash: m/d/y. – RobG Aug 30 '16 at 23:30

2 Answers2

1

var d = new Date('2016-08-27T17:40:09Z'),
    dFormatted = [d.getMonth() + 1, d.getDate(), d.getFullYear()].join('\\') + ' ' + [d.getHours(), d.getMinutes()].join(':');

console.log(dFormatted);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
0

If your format is very unique then you need to make your own formatter:

function toMyFormat(time) {
  var d = new Date(time);
  return d.getMonth() + '\\' + d.getDate() + '\\' + d.getFullYear() + ' ' + d.getHours() + ':' + d.getMinutes();
}
console.log(toMyFormat('2016-08-27T17:40:09Z'));

You may however be lucky enough to find a localeString format that suits you:

var d = new Date('2016-08-27T17:40:09Z');

console.log(d.toLocaleString('en-US'));
console.log(d.toLocaleString('da-DK'));
console.log(d.toLocaleString('de-GE'));
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28
  • Great thank you I was lucky enough, very appreciated. – EasyE Aug 30 '16 at 15:11
  • 1
    @EasyE the `d.getMonth()` returns the month (from 0-11), so this answer is wrong.. Check my solution – Yosvel Quintero Aug 30 '16 at 15:16
  • 2
    *toLocaleString* is implementation dependent so will return different results in different browsers (not to mention that `en-US` is not a "locale", it's a language). The above depends on support for the ECMA-402 internationalisation API, which is not supported by all browsers in use. – RobG Aug 30 '16 at 23:33