11

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.

Anconia
  • 3,888
  • 6
  • 36
  • 65

5 Answers5

27

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.

Johanna Larsson
  • 10,531
  • 6
  • 39
  • 50
3

do you have to subtract the hours from a string?

If not then:

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

If you do have to use a string I'd still be tempted to do:

var date= new Date("2014-05-15T16:55:56.730Z");
date.setHours(isodate.getHours() - 5);
var isoDate = new Date().toISOString();
Paul D'Ambra
  • 7,629
  • 3
  • 51
  • 96
1

For complex date operations and enhanced browser compatibility, I highly recommend using moment.js, especially if you're going to be doing several. Example:

var fiveHoursAgo = moment().subtract( 5, 'hours' ).toISOString();
ncksllvn
  • 5,699
  • 2
  • 21
  • 28
1

The way to modify Date objects is via functions such as Date.setHours, regardless of the format you then use to display the date. This should work:

var theDate = new Date();
theDate.setHours(theDate.getHours() - 5);
var isodate = theDate.toISOString();
Dan Korn
  • 1,274
  • 9
  • 14
  • You can certainly use libraries such as moment.js or Date.js if you wish, but this is easy enough to do with standard JavaScript. Either way though, the way you modify the number of hours has nothing to do with how the date may be formatted (such as ISO in your case). – Dan Korn May 15 '14 at 17:18
-1

Moment.js is perfect for this. You can do:

var date = new Date();
var newDate = moment(date).subtract('hours', 5)._d //to get the date object
var isoDate = newDate.toISOString();
Daniel Bernhard
  • 382
  • 3
  • 11