检测系统时间是不是与系统时区不对应 [Javascript]

Posted

技术标签:

【中文标题】检测系统时间是不是与系统时区不对应 [Javascript]【英文标题】:Detecting if the system time doesn't correspond to system timezone [Javascript]检测系统时间是否与系统时区不对应 [Javascript] 【发布时间】:2021-12-28 17:16:42 【问题描述】:

我有一个特定的系统配置,我的时区设置为 (UTC-03:00),但我将系统时间配置为一个小时后(例如:最初我使用时区的时间必须是 14:41,但我更新了到 15:41)。

我想知道是否有办法使用任何库来知道时间与时区不相关。

其他解决方案可能是使用 moment 或其他库使用系统时区而不是系统时间返回时间来解析时间。

我厌倦了使用 Datemomentmoment-timezone 没有运气。

例如:

系统时间:15:46(手动配置+1小时)

时区时间:14:46(如果没有更新,这应该是小时)

moment()  //result Wed Nov 17 2021 15:46:19 GMT-0300

我想要的是

moment().someFunc()  //result Wed Nov 17 2021 14:46:19 GMT-0300
// Could be a function, property, just a difference to use it in order 
//to compare with other date that comes from the server

【问题讨论】:

【参考方案1】:

如果您尝试获取 utc 日期时间(使用 moment().utc()),结果是您的时间减少了 utcOffset,并且文档中没有关于它的内容,所以我认为没有办法去做你想要的。

另一种方法是像下面的代码一样从外部服务器获取时间,但我希望其他人知道更好的方法

async function myTzTime() 
  const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  const  data:  datetime  =   = await axios.get(`http://worldtimeapi.org/api/timezone/$timezone`);
  

  console.log('--->', datetime)


myTzTime();
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.24.0/axios.min.js"></script>

【讨论】:

以上是关于检测系统时间是不是与系统时区不对应 [Javascript]的主要内容,如果未能解决你的问题,请参考以下文章