Question

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.

Était-ce utile?

La solution

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.

Autres conseils

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

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

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

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();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top