【问题标题】:Javascript wrong/different date time is extracted from the UTC converted dateJavascript 错误/不同的日期时间是从 UTC 转换日期中提取的
【发布时间】:2020-04-07 12:13:28
【问题描述】:

我有一个本地格式的日期,我将其更改为 UTC 格式。在 UTC 之后,我想在 UTC 中提取日期和时间。但是每当我试图提取时间或日期时,它只考虑本地时间,这是为什么呢?

          this.utcDate = this.datePipe.transform(this.onceDate,'medium');
          console.log('+=timezonenene=+', this.utcDate);

          this.utcDateStr = new Date(this.utcDate).toUTCString();
          console.log('++ date is ++', this.utcDateStr);

          this.utcDateStr = new Date(this.utcDateStr).toISOString();
          console.log('++ date is ++', this.utcDateStr);

          this.showDate = this.datePipe.transform(this.utcDateStr, 'yyyy-MM-dd');
          this.showTime = this.datePipe.transform(this.utcDateStr, 'HH:mm');
          console.log('+=time date zonenene date str =+', this.showDate);
          console.log('+=timezonenene date str=+', this.showTime);

输出:

+=timezonenene=+ Apr 7, 2020, 5:41:16 PM
++ date is ++ Tue, 07 Apr 2020 12:11:16 GMT
++ date is ++ 2020-04-07T12:11:16.000Z
+=time date zonenene date str =+ 2020-04-07
+=timezonenene date str=+ 17:41

我希望上次记录的时间为:12:11 而不是 17:41

【问题讨论】:

    标签: javascript angular timezone utc


    【解决方案1】:

    您的问题似乎与Angular DatePipe 相关(尽管您直接调用了transform 函数)。

    来自关于timezone 参数的文档:

    如果未提供,则使用最终用户的本地系统时区。

    因此,要获得 UTC 输出,您可以更改代码以在每次调用 datePipe.transform 时在格式参数之后提供时区参数 'UTC'

    另外,我会重新考虑为什么您生成字符串只是为了再次解析它们。通常这是不必要的,并且可能导致错误。如果this.onceDateDate 对象,您应该能够在整个代码中使用它,而不是创建this.utcDateStr 只是为了再次解析和转换它。 (虽然很难从您的代码中判断是否是这种情况。将来,请提供minimal, reproducible example。)

    【讨论】:

    • 当然可以,如果我们能直接得到utc时间,就不用转成utc字符串了,谢谢。
    猜你喜欢
    • 2019-09-07
    • 2011-07-11
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    相关资源
    最近更新 更多