javascript 当地时间

javascript luxon gmt time to locale

我在 gmt 区的数据库中有一个时间戳。如何根据用户时区显示时间?目前我有这样的时间

return luxon.DateTime.fromSQL(created_at).setZone('local');

它returns gtm 中的时间。

使用此方法解决的问题:

let offset = - (new Date().getTimezoneOffset() / 60);
return luxon.DateTime.fromSQL(created_at).plus({hours: offset}).toLocaleString(luxon.DateTime.TIME_SIMPLE)

一种更简洁的处理方式是只告诉解析器时间以 GMT 表示:

DateTime.fromSQL(current_time, {zone: "utc"}).toLocal()

再多解释一下,在您的原文中发生的事情是时间字符串应该被解释为 GMT 时间,但 Luxon 不知道这一点。因此它将字符串解释为本地时间,这与您所说的偏移时间不同。但如果 Luxon 知道 "this is expressed in GMT" 那么它就会在第一时间获得正确的时间。