Modifying an ISO Date in Javascript

Anconia picture Anconia · May 15, 2014 · Viewed 14.3k times · Source

I'm creating several ISO dates in a Javascript program with the following command:

var isodate = new Date().toISOString()

which returns dates in the format of "2014-05-15T16:55:56.730Z". I need to subtract 5 hours from each of these dates. The above date would then be formatted as "2014-05-15T11:55:56.730Z"

I know this is hacky but would very much appreciate a quick fix.

Answer

Johanna Larsson picture Johanna Larsson · May 15, 2014

One solution would be to modify the date before you turn it into a string.

var date = new Date();
date.setHours(date.getHours() - 5);

// now you can get the string
var isodate = date.toISOString();

For a more complete and robust date management I recommend checking out momentjs.