Modifying an ISO Date in Javascript
Asked Answered
B

5

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.

Buchalter answered 15/5, 2014 at 17:6 Comment(0)
H
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.

Hali answered 15/5, 2014 at 17:12 Comment(0)
D
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();
Dispersal answered 15/5, 2014 at 17:13 Comment(1)
Thank you, I'll be taking your approach!Buchalter
A
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();
Aerobiosis answered 15/5, 2014 at 17:14 Comment(3)
did you actually try this?Dorindadorine
I don't remember; this is pretty old. Is it not working for you?Aerobiosis
Yep, is deprecated, now is slightly different moment().subtract( 5, 'hours' ).toISOString();Dorindadorine
L
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();
Linkwork answered 15/5, 2014 at 17:16 Comment(1)
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).Linkwork
H
-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();
Holmen answered 15/5, 2014 at 17:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.