Andrey
Andrey

Reputation: 2729

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

Upvotes: 1

Views: 1863

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30675

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>

Upvotes: 2

Related Questions