Changing ISO Date in Javascript

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

var isodate = new Date().toISOString()

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

I know this is hacked, but I really appreciate the quick solution.

+4
source share
5 answers

One solution would be to change 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 reliable date management, I recommend checking momentjs .

+11
source

Do you need to subtract hours from a string?

If not, then:

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

, :

var date= new Date("2014-05-15T16:55:56.730Z");
date.setHours(isodate.getHours() - 5);
var isoDate = new Date().toISOString();
+2

moment.js, . :

var fiveHoursAgo = moment().subtract( 5, 'hours' ).toISOString();
+1

Date - , Date.setHours, , . :

var theDate = new Date();
theDate.setHours(theDate.getHours() - 5);
var isodate = theDate.toISOString();
+1

Moment.js . :

var date = new Date();
var newDate = moment(date).subtract('hours', 5)._d //to get the date object
var isoDate = newDate.toISOString();
0

Source: https://habr.com/ru/post/1540749/


All Articles