简体   繁体   中英

Parse UTC timestamp as local time, ignoring timezone

I got some dates formatted as UTC.

These dates are actually timestamps of events happened locally around the world in the users local time and not real UTC. (It has been done like this due to MongoDB limitations of storing local time)

On the frontend, I want to use these fields without converting them into browsers local time.

Date string received from the backend looks like this:

2018-10-09T18:02:25.000Z

Creating a date object will convert it to browser's local time:

const date = new Date("2018-10-09T18:02:25.000Z")
console.log(date.getHours()) // Prints 20 since Im in +2 timezone

I want it to ignore the Zulu timezone information. I could remove the Z like this:

function toDateIgnoreUTC(dateString) {
    return new Date(dateString.replace("Z", ""));
}

const date2  = toDateIgnoreUTC("2018-10-09T18:02:25.000Z")
date2.getHours() // Prints 18 which is what I want

I wonder if there's a better way of making the date object ignore the timezone information and not convert it to the browser local time.

I'll second deceze's concern that you're altering the meaning of the timestamp. But answering the question you asked:

The way you're doing it (by removing the Z ) is per specification . A date/time string in that format without timezone information is parsed as local time. However , beware that Apple's JavaScript engine gets this wrong , which impacts Safari (of course) but also all current iOS browsers (since they're currently forced to use Apple's JavaScript engine, not their own).

To address that, you can always parse it yourself (that format is quite simple) and use the new Date(year, monthMinusOne, day, hours, minutes, seconds) constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM