Luxon: how to disregard default timezone in a specific date
Asked Answered
M

2

19

I want to generate a Luxon date without taking the Settings.defaultZone into account.

In my case, I got a date string from a third party date picker component. The format is as the following:

2019-06-28T00:00:00

Now, however, we use Luxon through all our app to manage dates, so I need to parse that date to generate a Luxon one.

therefore, I parse the string as following:

import { DateTime } from 'luxon';
function parseDate(dateString) { // Let's say dateString === 2019-06-28T00:00:00

  const formattedDate = DateTime.fromISO(value); // 2019-06-27T23:00:00.000Z
 ...
}

As you can see, the formattedDate is affected by the current timezone. In this specific case, in the application bootstrap, we set the general timezone to GMT+1.

Therefore, the formatted date is set to 27 of june at 23:00, instead of 28 of june at 00:00, which is the date the user selects in the datepicker. The global timezone setting is tweaking with the time.

This is generally great, but in this specific case (the user is picking the expiration date of their id card) we don't need nor want to take timezones into account. I would like the date to be set to day 28 of june with utc timezone.

I tried this:

const formattedValue = DateTime.fromISO(value).setZone('utc');

However this does not modify the date and it is set to 27 of June.

I guess there is an easy way to achieve this, only I cannot find it.

Matazzoni answered 4/6, 2019 at 8:28 Comment(0)
M
19

I was real close:

const formattedValue = DateTime.fromISO(value, {zone: 'utc'});

Does the trick.

Matazzoni answered 4/6, 2019 at 8:30 Comment(2)
You can also put a Z on the end of your string, I imagine. That works for the system Date object. The format shown, with no Z, is time zone not defined. It's a format to avoid. At one point, chrome would interpret this as local and safari as UTC. Nightmare. I don't know if this is still the case.Desberg
The "Z" works too, but there's a subtle difference. They both would interpret the string as the same moment in time, but the one here also sets the zone of the DT instance to UTC, whereas the Z one leaves it as local, meaning, e.g. that the hour accessor would give you back the local time. moment.github.io/luxon/docs/manual/…Stevana
P
0

I know that is it old-top but for someone with similar problem, just use toISODate()

For example:

const firstDayOfYear = (year) => luxon.DateTime.fromObject({ year, month: 1, day: 1 });
const year = firstDayOfYear(2015).toISODate() // will equal '2015-12-31'

From docs:

DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'
DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'
Parasiticide answered 9/3, 2022 at 7:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.