简体   繁体   中英

How to get string representation of date in Luxon with specified timezone

I need to display dates in my web application with PST timezone. It should not be dependent of the timezone of the user.

I tried the following code:

const dateTime = DateTime.fromISO('2022-03-22T15:00:00.000Z');
dateTime.setZone("America/Los_Angeles");
console.log(dateTime.toLocaleString(DateTime.DATETIME_FULL));

But anyway, it displays:

March 22, 2022, 4:00 PM GMT+1

How possible to get output in timezone defined?

Thank you

DateTimes are immutable in luxon, so the.setZone() call will not change your original dateTime variable, rather it will return a new value.

I'd suggest setting the zone in the .fromISO() call:

 const { DateTime } = luxon; const dateTime = DateTime.fromISO('2022-03-22T15:00:00.000Z', { zone: "America/Los_Angeles" }); console.log(dateTime.toLocaleString(DateTime.DATETIME_FULL)); console.log(dateTime.toISO());
 .as-console-wrapper { max-height: 100%;important; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js" integrity="sha512-Nw0Abk+Ywwk5FzYTxtB70/xJRiCI0S2ORbXI3VBlFpKJ44LM6cW2WxIIolyKEOxOuMI90GIfXdlZRJepu7cczA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Or you could call.setZone() on the result of the.fromISO() call:

 const { DateTime } = luxon; const dateTime = DateTime.fromISO('2022-03-22T15:00:00.000Z').setZone( 'America/Los_Angeles' ); console.log(dateTime.toLocaleString(DateTime.DATETIME_FULL)); console.log(dateTime.toISO());
 .as-console-wrapper { max-height: 100%;important; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js" integrity="sha512-Nw0Abk+Ywwk5FzYTxtB70/xJRiCI0S2ORbXI3VBlFpKJ44LM6cW2WxIIolyKEOxOuMI90GIfXdlZRJepu7cczA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM