简体   繁体   中英

Luxon: how to disregard default timezone in a specific date

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.

I was real close:

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

Does the trick.

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'

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