0

I have checked so many places but could not find a proper answer. I have to get current time in UTC and then subtract few days (say 2 days). So if today is 25th March, I would like to get data of past 2 days starting from 23rd March 00:00 hours GMT.

I can get individual hours and minutes in GMT. But the moment I do new Date() it gives me in local timestamp. Normally I would subtract the current GMT hours and minutes from current time and the number of days I have to subtract.

But when I do a new Date() instead of GMT I get local time. I can do toUTCString() but that is after getting the time in my local time format. If I subtract my local time too then my code won't work universally.

So I need to get the new Date() function in UTC format. I checked a lot of places but nothing seems to work.

James Z
  • 12,209
  • 10
  • 24
  • 44
Saurav Rath
  • 91
  • 1
  • 3
  • 11

2 Answers2

2

The getTime method will return a number representing the milliseconds elapsed from the epoch (1 January 1970 00:00:00 UTC). This method always uses UTC for time representation.

Then you could subtract 2 days and get another Date instance:

var timestamp = new Date().getTime();
timestamp = timestamp - 2 * 24 * 60 * 60 * 1000;
var newDate = new Date(timestamp);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

I recommend you use Moment.js to operate with Dates.

In particular adding or subtracting dates is very easy using this library, for example:

moment().subtract(2, 'days')

If you want to do it natively, there are many ways to do it, but one of them is this:

const d = new Date();
d.setDate(d.getDate() - 2);

About UTC date:

But the moment I do new Date() it gives me in local timestamp

That's just a string representation, that is different depending on the environment. Dates are stored internally in UTC, so there is no problem using new Date() and operating with it.

Antonio Val
  • 3,200
  • 1
  • 14
  • 27
  • You should use moment.utc() to generate a new date in UTC format – Victor Mar 25 '18 at 14:58
  • it depends on what you want to accomplish. It seems that he wants to get current UTC time, so it should not be necessary. – Antonio Val Mar 25 '18 at 15:00
  • yes i didn't require moment.utc(). But you were correct about new Date(). Its just a string representation and internally its UTC. I deployed my code in different servers running on different timezones and bot gave correct results as per UTC. Thanks a lot. – Saurav Rath Mar 30 '18 at 04:20