0

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.

nilsi
  • 10,351
  • 10
  • 67
  • 79
  • 1
    `.getUTCHours()` instead of `.getHours()`? – VLAZ Jun 05 '19 at 07:54
  • 3
    If the timestamps says it's in Zulu time, arbitrarily interpreting it as local time instead changes the meaning of the timestamp. I.e. 18:02 UTC is not the same time as 18:02 New York. Either the timestamp shouldn't have a Z in the first place, or what you're doing is arbitrarily altering it. No? – deceze Jun 05 '19 at 07:57
  • 1
    @deceze it's absolutely altering it and dropping relevant information. That *could* work and it wouldn't be a problem...until it is. The moment a user travels to a new timezone, you have an irreversible problem. – VLAZ Jun 05 '19 at 07:59

1 Answers1

4

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875