-1

I have a date in UTC in javascript, and I would like to substract some hours.

I searched online and apparently I should concat the substraction to the date like the following:

const diff = "-5"
const utcDate = "2017-02-22 17:28:13"
const date = new Date(utcDate + diff[0] + ' ' + diff[1])
//desired output: 2017-02-22 12:28:13

But I can't seem to make it work.

2 Answers2

0
someDate.setHours(someDate.getHours()+1);

From https://stackoverflow.com/a/1050782/537998

Kirk Strobeck
  • 17,984
  • 20
  • 75
  • 114
0

I do all my Date calculations with .getTime(). So an hour is 3600000 milliseconds.

const MILLISECONDS_HOUR = 3600000;

const diff = -5;
const utcDate_str = "2017-02-22 17:28:13";

const utcDate = new Date( utcDate_str );

const minus_5_hours = new Date( utcDate.getTime() + ( MILLISECONDS_HOUR * diff ));

console.log( utcDate.toJSON());
console.log( minus_5_hours.toJSON());

The big advantage is that javascript will take care of leap years, month boundaries and such.

But since you are calling your variable diff, are you trying to calculate lcoal time vs UTC time?

In that case, reread the javascript Date methods. There's a bunch of methods to handle both UTC and local time, for example: date.getUTCDate() and date.getDate().

So you might not have to calculate all of this yourself.

Also, if you format your dates according to the ISO, "2017-02-22T17:28:13.000Z", this will automatically get parsed as UTC.

Shilly
  • 8,511
  • 1
  • 18
  • 24