user3339562
user3339562

Reputation: 1385

Retrieve UTC timestamp with Javascript

I have an app where I don't care about time zones and need only UTC time. This means my timestamps need to match UTC time.

My goal is to get 2 UTC timestamps for current day. Let's say UTC time is June 21st 13:04:47.

For this time I would like to get timestamp for midnight of that day June 21st 00:00:00 and timestamp for 24 hours later June 22nd 00:00:00. Timestamps for those two times are 1466467200000 and 1466553600000.

This is how I am currently doing it:

    var today = new Date();
    var todayStart = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate(), 0, 0, 0));
    var todayEnd = new Date();
    todayEnd.setTime(todayStart.getTime() + (24 * 60 * 60 * 1000));

    console.log("start of the day: " + todayStart.getTime())
    console.log("end of the day: " + todayEnd.getTime());

This returns correct results but I am wondering is this reliable and is it the right way to accomplish what I want. Thank you for your help.

Upvotes: 0

Views: 358

Answers (2)

YemSalat
YemSalat

Reputation: 21486

I would strongly discourage use of native Date object for this.

Check out moment and moment-timezone - they cover all your use cases out of the box: http://momentjs.com/

With that you can do: moment().tz('Europe/Berlin').utc()

Upvotes: 1

Useless Code
Useless Code

Reputation: 12402

The way you are doing it works and should be reliable. If I had written it I would have done it a little differently.

var start = new Date(),
  end;

// set midnight today
start.setUTCHours(0);
start.setUTCMinutes(0);
start.setUTCSeconds(0);
start.setUTCMilliseconds(0);

// set to midnight tomorrow
end = new Date(start);
end.setUTCDate(start.getUTCDate() + 1);

console.log("start of the day: " + start.getTime());
console.log("end of the day: " + end.getTime());

This code creates the start date as the current date/time and then zeros out the time portions. Then getting 24 hours later is just a matter of creating a duplicate Date and incrementing the date by 1. It does require a little more code but it makes it explicit what you are doing and will probably be easier to read and comprehend when maintaining the code in the future.

Upvotes: 1

Related Questions