【问题标题】:How can i fix timezone issue while using date format in moment.js?在 moment.js 中使用日期格式时如何解决时区问题?
【发布时间】:2021-04-20 09:24:49
【问题描述】:

这是我输入的日期, let inputDate = '2021-01-15T11:22:10.000Z'。 我想将日期格式更改为MM/DD/YYYY HH:mm:ss 为此,我使用了以下我使用了 moment.js 。这是我的代码,

moment(inputDate).format('MM/DD/YYYY HH:mm:ss') = 01/15/2021 16:52:10

格式化日期后,我得到了添加时区的日期。如何获得 MM/DD/YYYY HH:mm:ss 格式的确切时间?

我也尝试了以下方法;

moment(inputDate).local(true).format('MM/DD/YYYY HH:mm:ss')
moment(inputDate).utcOffset(330).format('MM/DD/YYYY HH:mm:ss')
moment(inputDate).utcOffset(0).format('MM/DD/YYYY HH:mm:ss')
moment(inputDate).utcOffset("+05:30").format('MM/DD/YYYY HH:mm:ss')
moment(inputDate).utcOffset("-05:30").format('MM/DD/YYYY HH:mm:ss')

请帮我解决问题。

【问题讨论】:

    标签: datetime timezone momentjs date-format moment-timezone


    【解决方案1】:

    您应该告诉 moment 您提供的日期是 UTC。您可以使用utc() 函数来实现这一点:

    moment.utc(inputDate)
    

    如果您在utc() 之后格式化,您将看到UTC 时区的日期:

    moment.utc(inputDate).format('MM/DD/YYYY HH:mm:ss')
    

    let inputDate = '2021-01-15T11:22:10.000Z';
    
    console.log(moment.utc(inputDate).format('MM/DD/YYYY HH:mm:ss'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 2020-11-22
      相关资源
      最近更新 更多