【问题标题】:Convert time format 2019-01-21 05:05:11.000000 to 1548060780546将时间格式 2019-01-21 05:05:11.000000 转换为 1548060780546
【发布时间】:2019-01-22 10:47:19
【问题描述】:

在我的 Angular 应用程序中,我从后端 API 获取的记录时间为 2019-01-21 05:05:11.000000(时区 = UTC 和 timezone_type = 3)。以同样的方式,我使用以下代码获取当前时间。

const now = new Date();
const currentTime = now.getTime();

我得到了当前时间的输出“1548152940836”。

我使用getTimezoneOffset()方法返回UTC时间与本地时间的时差。

  const loggedTime = new Date(lastLoginAt).getTime();
  const now = new Date();
  const currentTime = now.getTime();

 if ((currentTime - (loggedTime - (new Date()).getTimezoneOffset()*60*1000)) > (7200 * 1000)){ }

在我的应用程序中,我想获取记录时间和当前时间之间的时间差,并检查该时间差是否大于 7200 秒。 但这给了我很大的时间差,总是大于 7200,000 毫秒。

【问题讨论】:

    标签: javascript date timestamp


    【解决方案1】:

    如果您的lastLoginAt 字符串的格式与2019-01-21 05:05:11.000000 完全相同,并且表示UTC 时间戳,那么您首先需要在解析之前将其更改为2019-01-21T05:05:11.000000Z。这是 ECMAScript 规范要求的 ISO 8601 扩展 UTC 格式(也是 RFC 3339)。

    然后您可以简单地减去时间戳。无需调整时区偏移,因为这两个值都是基于 UTC 的。

    (为方便起见,您还可以使用Date.parseDate.now 而不是分配Date 对象实例。两者都返回数字时间戳。)

    const loggedTime = Date.parse(lastLoginAt.replace(' ', 'T') + 'Z');
    const currentTime = Date.now();
    
    if (currentTime - loggedTime > 7200000) {
    
    }
    

    或者,考虑使用诸如Luxondate-fns 之类的库,它们提供的函数可以使这变得更加容易。

    【讨论】:

      猜你喜欢
      • 2012-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-10
      相关资源
      最近更新 更多