【问题标题】:dayjs() is in the wrong timezonedayjs() 的时区错误
【发布时间】:2021-10-13 08:27:42
【问题描述】:

问题

调用dayjs() 会得到一个正确的日期,只是它相差两个小时。出于某种原因,dayjs() 似乎设置为错误的时区 (GMT),而我的实际时区是 GMT+2。

预期

Mon, 09 Aug 2021 17:45:55 GMT+2

实际

Mon, 09 Aug 2021 15:45:55 GMT

我尝试过的

我尝试使用the time zone plugin 设置我的时区,但这似乎不起作用:

import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs().tz('Europe/Berlin'); // unchanged Mon, 09 Aug 2021 15:45:55 GMT

我使用的是 Ubuntu 20.04.2 LTS,所以我检查了:

$ timedatectl 
Local time: Mo 2021-08-09 17:45:55 CEST
Universal time: Mo 2021-08-09 15:45:55 UTC 
RTC time: Mo 2021-08-09 17:45:55     
Time zone: Europe/Berlin (CEST, +0200)
System clock synchronized: yes                        
NTP service: active                     
RTC in local TZ: yes                        

Warning: The system is configured to read the RTC time in the local time zone.
This mode cannot be fully supported. It will create various problems
with time zone changes and daylight saving time adjustments. The RTC
time is never updated, it relies on external facilities to maintain it.
If at all possible, use RTC in UTC by calling
'timedatectl set-local-rtc 0'.

我正在使用 TypeScript 进行编码,因此我还检查了创建 Date 对象是否也会导致错误的时间,但它没有:

const time = new Date(); // results in correct time

TL;DR

dayjs() 是 GMT,但应该是 GMT+2。为什么?

【问题讨论】:

  • 当您执行new Date('Mon, 09 Aug 2021 17:45:55 GMT+2')new Date('Mon, 09 Aug 2021 15:45:55 GMT') 时,生成的日期对象是什么?它们有何不同?
  • 它们的结果是一样的:1:Mon Aug 09 2021 17:45:55 GMT+0200 (Central European Summer Time) 2:Mon Aug 09 2021 17:45:55 GMT+0200 (Central European Summer Time)
  • 在您的问题中,您说它“关闭了两个小时”。它关闭了 2 小时还是相同的确切时间?您可以将您的存储为 GMT 吗?
  • 我的问题是 dayjs 似乎走错了当地时间。我的问题是,如果我在另一台机器上运行相同的代码,它就不再工作了,因为在那台机器上本地时间正常工作。
  • 所以你说如果一台机器在德国,另一台机器在英国,你创建新的日期并存储那些 utc/iso 字符串值,然后在另一台机器上使用这些字符串,结果在不同的时间?不是本地的,不同的 UTC/ISO 时间。当地时间可以“不同”,但如果它们生成相同的 iso/utc 字符串,那么它们是一样的吗?

标签: javascript linux typescript ubuntu dayjs


【解决方案1】:

简单地使用没有时区插件的 utc 插件就可以达到预期的效果。

import utc from 'dayjs/plugin/utc';
day.extend(utc);
dayjs.utc(); // results in date in correct timezone

【讨论】:

    【解决方案2】:

    这对我有用。

    dayjs('2021-08-09 15:45:55 UTC').tz("Africa/Lagos")
    

    回应

    {
      '$L': 'en',
      '$offset': 60,
      '$d': 2021-08-09T15:45:55.000Z,
      '$x': { '$timezone': 'Africa/Lagos' },
      '$y': 2021,
      '$M': 7,
      '$D': 9,
      '$W': 1,
      '$H': 16,
      '$m': 45,
      '$s': 55,
      '$ms': 0
    }
    

    【讨论】:

      猜你喜欢
      • 2022-07-27
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 2022-11-14
      • 2021-03-29
      • 2022-11-11
      • 2015-12-25
      • 1970-01-01
      相关资源
      最近更新 更多