Home > Back-end >  JS - Convert a "Europe/Berlin"-Date into a UTC-Timestamp
JS - Convert a "Europe/Berlin"-Date into a UTC-Timestamp

Time:05-22

Inside my Docker-Container, which has the timezone Etc/UTC, I need to convert a Date-String which represents a Date in Europe/Berlin-timezone into a UTC timestamp.

So lets say the Europe/Berlin-Date is 2022-04-20T00:00:00.

Now the UTC-Timestamp should be equivalent to 2022-04-19T22:00:00.

But when I do

console.log(new Date("2022-04-20").getTime())

I get 1650412800000 which is equivalent to 2022-04-20T02:00:00 in Europe/Berlin-timezone.

How would I do this?

Edit:

I tried various libs, but still cant get that managed

const { DateTime } = require("luxon")


var f = DateTime.fromISO("2022-04-20").setZone('Europe/Berlin').toUTC()
console.log(f)

also the equivalent stamp in f is 2022-04-20T02:00:00 :/

CodePudding user response:

I need to convert a Date-String which represents a Date in Europe/Berlin-timezone into a UTC timestamp.

Fundamentally, a date-only value cannot be converted into a timestamp, unless you arbitrarily associate a time with that date. It sounds like you meant to use midnight local time (00:00 02:00) but instead you are seeing midnight UTC (00:00Z).

This is due to how you are constructing the Date object. You specify new Date("2022-04-20"), which according to the ECMASCript spec will be treated as midnight UTC. The spec says:

... When the UTC offset representation is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.

Yes, this is inconsistent with ISO 8601, and that has been discussed ad nauseum.

To solve this problem, append T00:00 to your input string, so that you are specifically asking for local time. In other words, new Date("2022-04-20T00:00").

That said, if you need it to not be "local time" but exactly Europe/Berlin, then yes - you'll need to use a library. In luxon, it's like this:

DateTime.fromISO('2022-04-20T00:00', {zone: 'Europe/Berlin'}).toUTC()
  • Related