Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying an ISO Date in Javascript

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.

like image 367
Anconia Avatar asked May 15 '14 17:05

Anconia


People also ask

What is ISO date format in JavaScript?

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ , respectively). The timezone is always zero UTC offset, as denoted by the suffix Z .

How do I change a date to ISO?

The date. toISOString() method is used to convert the given date object's contents into a string in ISO format (ISO 8601) i.e, in the form of (YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss.

How do I convert ISO date to local time?

Use the getTime() method to convert an ISO date to a timestamp, e.g. new Date(isoStr). getTime() . The getTime method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation.


1 Answers

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.

like image 88
Johanna Larsson Avatar answered Sep 27 '22 16:09

Johanna Larsson