Abana Clara
Abana Clara

Reputation: 4650

Get current timestamp from specific date using UTC/GMT+0 as epoch ignoring local time zone epoch

I've tried a lot from this community but it seems like there's no hyper specific scenario for my case.

So basically I have a string in the format of yyyy-mm-dd. I use date methods to adjust it and add time on the date to make it more specific. I want to convert it to timestamp while ignoring the client computer's current timezone (or using UTC timezone).

I have this code:

function getTimestampRange(sparams, eparams){

sparams = "2018-11-12", eparams = "2018-11-13"; //sample param values

const start = sparams.split("-");
const end = eparams.split("-");

const startDate = new Date(start[0], start[1] - 1, start[2]);
const endDate = new Date(end[0], end[1] - 1, end[2]);
endDate.setHours(23);
endDate.setMinutes(59);
endDate.setSeconds(59);

//startDate is 2018-11-12 00:00:00 and endDate is 2018-11-13 23:59:59

const startTS = startDate.getTime() / 1000;
const endTS = endDate.getTime() / 1000;

return [startTS, endTS]
}

This is all fine and dandy but the problem is, I'm getting the timestamp relative to my computer's timezone. (GMT+9). So my epoch is the 9th hour of 1970-01-01. Which is not what I need. I need the GMT+0 UTC timestamp.

In this scenario, I'd get 1541948400 and 1542121199, start and end respectively; where I should be getting 1541980800 and 1542153599.

Tasukete kudasai

Upvotes: 2

Views: 1342

Answers (1)

Phil
Phil

Reputation: 164736

You have two options here...

  1. Use Date.UTC to construct timestamps in UTC

    const startDate = Date.UTC(start[0], start[1] - 1, start[2]) // a timestamp
    const endDate = Date.UTC(end[0], end[1] - 1, end[2], 23, 59, 59) // a timestamp
    

    Note: Date.UTC() produces a timestamp in milliseconds, not a Date instance. Since you're able to set the hours, minutes and seconds as above, you no longer need to manipulate those.

  2. Use your existing date strings which adhere to the ISO 8601 standard as the sole argument to the Date constructor.

    This benefits from this particular nuance...

    Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

    const startDate = new Date(sparams)
    const endDate = new Date(eparams)
    

    Parsing ISO 8601 is supposedly supported in all decent browsers and IE from v9. Since this relies on a particular "feature" that may or may not be implemented in a client, there is an element of risk to this method.


For your end date, if parsing you can easily append a time and zone portion to the date string rather than manipulate the date object with hour, minute and second values. For example

const endDate = new Date(`${eparams}T23:59:59Z`)

alternatively, use Date.prototype.setUTCHours()...

const endDate = new Date(eparams)
endDate.setUTCHours(23, 59, 59)

Upvotes: 2

Related Questions