admin管理员组

文章数量:1301575

I've a timestamp from my database at the gmt zone. How can I display the time based on the user timezone? Currently I`m getting the time like this

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

It returns the time in gtm.

I've a timestamp from my database at the gmt zone. How can I display the time based on the user timezone? Currently I`m getting the time like this

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

It returns the time in gtm.

Share edited Oct 17, 2018 at 18:56 Asif 3502 silver badges10 bronze badges asked Oct 17, 2018 at 18:44 MarkusMarkus 2,0604 gold badges29 silver badges64 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10

A cleaner way to handle it is to just tell the parser that the time is expressed in GMT:

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

To explain that a bit more, what's happening in your original is that the time string is meant to be interpreted as a GMT time, but Luxon doesn't know that. So it interprets the string as a local time, which is off from the time you meant by the offset. But if Luxon knows "this is expressed in GMT" then it will get the right time in the first place.

Problem solved by using this method:

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

本文标签: javascript luxon gmt time to localeStack Overflow