时刻和时区转换本地时间失败

Moment & Timezone convert local time fails

这是基于 NodeJS 的基于 Ionic 的混合应用程序。

正在尝试将用户输入指定的本地时间转换为另一个时区,但失败了:

static MTL_local_time_to_server(aDateTime:moment.Moment):moment.Moment{
    console.log(aDateTime.format('MMMM Do YYYY, h:mm:ss a'));

    const localTime:moment.Moment = momenttz.tz(aDateTime, momenttz.tz.guess());
    console.log(localTime.format('MMMM Do YYYY, h:mm:ss a'), momenttz.tz.guess());
    const returnTime:moment.Moment = momenttz(localTime).tz("Europe/Berlin");
    console.log(returnTime.format('MMMM Do YYYY, h:mm:ss a'));
    return returnTime;
}

版画

April 22nd 2019, 12:00:00 am 
April 22nd 2019, 12:00:00 am America/Los_Angeles 
April 22nd 2019, 9:00:00 am

几件事:

  • 您将 moment.tz 的输出键入为 string,但它实际上是一个 Moment 对象。

  • 当您在 Moment 对象上调用 JSON.stringify 时,它 returns .toISOString() 的输出,始终采用 UTC。 (Z 表示 ISO 8601 格式的 UTC。)

  • 不清楚您的输入是 string 还是 Date 对象。如果它是 string,那么 Z 表示 UTC,因此它将始终被解释为 UTC。如果它是一个 Date 对象,那么将使用该 Date 对象表示的时间点 - 这取决于您如何构造 Date 对象。无论哪种方式,您显示的值都是基于 UTC,而不是本地时间。

  • 不清楚您要完成什么。从你的变量名来看,你似乎正在尝试将 localDateTime 转换为 localTime,如果它们都是 "local".

    ,那么逻辑上会给出相同的值
    • 如果您尝试将值从本地时间转换为柏林时间,则:

      moment(yourInput).tz('Europe/Berlin')
      
    • 如果您尝试将值从洛杉矶时间转换为柏林时间,则:

      moment.tz(yourInput, 'America/Los_Angeles').tz('Europe/Berlin')
      
    • 如果您尝试将值从 UTC 转换为本地时间,则根本不需要时刻时区:

      moment.utc(yourInput).local()
      
  • 如果你需要字符串输出,那么你应该调用format函数来产生一个字符串。您在此处显示的内容看起来像是在记录 Moment 个对象而不是字符串。