简体   繁体   English

Luxon:如何忽略特定日期的默认时区

[英]Luxon: how to disregard default timezone in a specific date

I want to generate a Luxon date without taking the Settings.defaultZone into account.我想在不考虑Settings.defaultZone的情况下生成 Luxon 日期。

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.但是,现在我们在所有应用程序中都使用 Luxon 来管理日期,因此我需要解析该日期以生成一个 Luxon。

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.如您所见, formattedDate受当前时区的影响。 In this specific case, in the application bootstrap, we set the general timezone to GMT+1.在这种特定情况下,在应用程序引导程序中,我们将一般时区设置为 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.因此,格式化日期设置为 6 月 27 日 23:00,而不是 6 月 28 日 00:00,这是用户在日期选择器中选择的日期。 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.我想将日期设置为 6 月 28 日,使用 utc 时区。

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.但是,这不会修改日期并将其设置为 6 月 27 日。

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()我知道这是旧的,但对于有类似问题的人,只需使用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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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