Search code examples
javascripttimestamputc

Create UTC date in JavaScript, add a day, get unix timestamp


I'm trying to build dates in UTC in JavaScript, while specifying an hour and minute then getting a timestamp of it.

For example, If I have the hour of 15 and the minute of 25, I'm doing this:

var to_date = new Date();
to_date.setUTCHours(15);
to_date.setUTCMinutes(25);
var to_utc = new Date(to_date.getUTCFullYear(), 
              to_date.getUTCMonth(), 
              to_date.getUTCDate(), 
              to_date.getUTCHours(), 
              to_date.getUTCMinutes(), 
              to_date.getUTCSeconds());
var to_unix = Math.round(to_utc.getTime() / 1000);
console.log(to_unix);

The problem is this doesn't seem to be returning the right timestamp. It's setting the time not in UTC, but for my timezone. Any idea how to maintain this in UTC?

I also want to add a day to the time if it's past the current time. I've tried checking against the current and adding 60*60*24, but this returned minutes/hours that didn't match what I specified.

Any help would be great!

Thank you


Solution

  • If you're tinkering with an existing date object:

    var d = new Date();
    d.setUTCHours(15);
    d.setUTCMinutes(25);
    d.setUTCSeconds(0);
    

    d will now represent today at 15:25 UTC.

    If you're starting from scratch:

    var d = new Date(Date.UTC(year, jsmonth, day, utchour, utcminute, utcsecond));
    

    To get a unix timestamp, use getTime, which returns the number of milliseconds since epoch UTC, then divide by 1000 to convert to unix time (which is in seconds rather than milliseconds):

    Math.round(d.getTime() / 1000);
    

    Date.now() gives you the current time in UTC since epoch in milliseconds. To add a day and see if it is in the future:

    d.getTime() + (1000*60*60*24) > Date.now()