将TimeZone时间字符串正确转换为本地时间

时间:2020-09-21 07:10:21

标签: javascript reactjs date timezone momentjs

我正在尝试转换从后端系统返回的时间字符串,但无法获取正确的本地时间。

从后端返回的时间字符串:"2020-08-28T07:00:00.000Z"

预计所需的当地时间:Aug 28, 2020 12:00 AM

我尝试过:

  1. 使用Moment.js进行转换失败:

        moment(backendTime).format(
         "MMM D,YYYY h:mm a"
      ) 
    

    我以某种方式收到了“ 1月1日20 12:00 AM”,我一点都不明白

  2. 通过强制转换为Date进行转换也失败:

  Date("2020-08-28T07:00:00.000Z")

最终得到:“ 2020年9月21日星期一9:07:29 GMT-0700(太平洋夏令时)”

我现在的想法已经用光了,我觉得这不应该那么困难,但是根本无法理解。

3 个答案:

答案 0 :(得分:0)

您得到的格式正是您所要求的。

要使用moment.js获得所需的输出,您需要使用以下格式:

moment(backendTime).format("MMM DD, YYYY hh:mm A");

您可以在这里进行测试:https://jsfiddle.net/oz6mx3nh/

答案 1 :(得分:0)

在香草JS中,您可以使用DateTimeFormat来根据时区格式化日期。 DateTimeFormat的所有选项均为documented here

语言环境(en-US)的不同选项是listed here

这里是所有时区的full list

有关每个语言环境的输出,请参见下面的代码段(在提供的列表中)

const date = new Date("2020-08-28T07:00:00.000Z");

const format = new Intl.DateTimeFormat(
  "en-US",
  {
    month: "short",
    day: "2-digit",
    year: "numeric",
    hour: "2-digit",
    hour12: true,
    minute: "2-digit",
    timeZone: "America/New_York",
  }
).format(date)

console.log(format);

每个语言环境的输出列表:

const date = new Date("2020-08-28T07:00:00.000Z");

const locales = ["ar-SA", "bn-BD", "bn-IN", "cs-CZ", "da-DK", "de-AT", "de-CH", "de-DE", "el-GR", "en-AU", "en-CA", "en-GB", "en-IE", "en-IN", "en-NZ", "en-US", "en-ZA", "es-AR", "es-CL", "es-CO", "es-ES", "es-MX", "es-US", "fi-FI", "fr-BE", "fr-CA", "fr-CH", "fr-FR", "he-IL", "hi-IN", "hu-HU", "id-ID", "it-CH", "it-IT", "jp-JP", "ko-KR", "nl-BE", "nl-NL", "no-NO", "pl-PL", "pt-BR", "pt-PT", "ro-RO", "ru-RU", "sk-SK", "sv-SE", "ta-IN", "ta-LK", "th-TH", "tr-TR", "zh-CN", "zh-HK", "zh-TW"];

const formatDate = (locale, date) => new Intl.DateTimeFormat(
  locale,
  {
    month: "short",
    day: "2-digit",
    year: "numeric",
    hour: "2-digit",
    hour12: true,
    minute: "2-digit",
    timeZone: "America/New_York",
  }
).format(date);

// Loop over each locale
for(const locale of locales) {
  const formatted = formatDate(locale, date);
  
  console.log(`${locale}: ${formatted}`);
}

答案 2 :(得分:0)

几件事:

  • 假设您的计算机设置为太平洋时间,则:

    moment("2020-08-28T07:00:00.000Z").format("MMM D, YYYY h:mm a")
    //=> "Aug 28, 2020 12:00 am"
    

    这确实会返回您期望的值。您说您得到了"Jan 1st 20 12:00 AM",但这是不可能的,因为值和格式都不匹配。

  • 尝试使用Date对象时,得到的结果是您做的,因为您省略了new关键字(see this explanation)。相反,它应该是:

    new Date("2020-08-28T07:00:00.000Z")
    

    请记住,这会产生一个Date对象。如果直接记录该对象,则结果是特定于实现的。可能会因浏览器而异。相反,您应该从中调用诸如toStringtoLocaleString之类的函数。

  • 如果这是一个新项目,则应避免使用Moment。请阅读https://momentjs.com/docs/#/-project-status/

相关问题