EasyE EasyE - 3 months ago 12
Javascript Question

Formatting a date from Date.parse(dateString) in another format

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.

Answer

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'));

Comments