'Luxon setZone not working when getting epoch time (valueOf)

I have been trying to use Luxon to get (for comparison reasons) the epoch miliseconds from two DateTimes in different timezone.

I'm using the .valueOf() method to do so, but even that I'm setting the different timezones for each DateTime, that method always return the same value:

const { DateTime } = require('luxon')

const dtString = '2022-01-15 13:00:00'

const d1 = DateTime.fromSQL(dtString).setZone('America/Sao_Paulo').valueOf()
const d2 = DateTime.fromSQL(dtString).setZone('America/New_York').valueOf()

console.log(d1) // logs 1642262400000
console.log(d2) // logs 1642262400000 (same)

What is wrong?



Solution 1:[1]

Instead of parsing the dates in one zone and then shifting the times around, just parse them in the zone you want:

const dtString = '2022-01-15 13:00:00';
const d1 = DateTime.fromSQL(dtString, { zone: "America/Sao_Paulo" }).valueOf();
const d2 = DateTime.fromSQL(dtString, { zone: "America/New_York" }).valueOf();

d1 //=> 1642262400000
d2 //=> 1642269600000

The difference there is that in yours, Luxon parses the string using your system zone. Then you change the zone, but the time is still the time, unless you use keepLocalTime. In mine, I'm telling Luxon what zone to use in interpreting the string, which results in a different time being computed for the two cases.

Solution 2:[2]

Based on this Luxon issue, I found the fix for that:

We should use the keepCalendarTime: true option in the setZone method to make it work.

That extra flag says "yes, change the actual time"

So the functional code looks like:

const { DateTime } = require('luxon')

const dtString = '2022-01-15 13:00:00'
const opts = { keepCalendarTime: true }

const d1 = DateTime.fromSQL(dtString).setZone('America/Sao_Paulo', opts).valueOf()
const d2 = DateTime.fromSQL(dtString).setZone('America/New_York', opts).valueOf()

console.log(d1) // logs 1642262400000
console.log(d2) // logs 1642269600000 (prints different value)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 snickersnack
Solution 2 Arthur Borba