如何使用 JavaScript 中的 moment 将 GMT 转换为本地时间? [英] How to convert GMT to Local Time using moment in JavaScript?

查看:55
本文介绍了如何使用 JavaScript 中的 moment 将 GMT 转换为本地时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用月日(th/st) Year Hour:mm am/pm"格式将2019-07-15T08:57:58.749081"格式的时间转换为当地时间. 因此,诸如2018 年 9 月 9 日晚上 9:40"或2019 年 7 月 18 日晚上 9:40"等之类的内容

I'm trying to convert a time in the format of '2019-07-15T08:57:58.749081' to a local time using the format of 'Month Day(th/st) Year Hour:mm am/pm". So anything like "September 9th 2018 9:40 pm" or "July 18th 2019 9:40 pm", etc.

这是使用导入 ReactJS 应用程序的 moment 包.我可以让格式看起来正确,但时间仍然是 GMT/UTC.要执行此格式,我使用var dateTime = moment(param).format('MMMM Do YYYY h:mm a');

This is to use the moment package imported into a ReactJS app. I can get the format to look right but the time is still GMT/UTC. To do this format I used var dateTime = moment(param).format('MMMM Do YYYY h:mm a');

但我真的需要我自己本地时间的格式化时间.

But I really need the formatted time in my own local time.

推荐答案

由于输入字符串为 ISO 8601 格式,时间基准为 UTC,因此字符串应包含尾随 Z.换句话说,它应该看起来像 2019-07-15T08:57:58.749081Z.既然没有,你有两个选择.

Since the input string is in ISO 8601 format, and the time basis is UTC, the string should contain a trailing Z. In other words, it should look like 2019-07-15T08:57:58.749081Z. Since it doesn't, you have two choices.

  • 您可以自己附加Z:

moment(param + 'Z').format('MMMM Do YYYY h:mm a')

  • 您可以解析为UTC,然后在格式化之前切换到本地模式:

  • You can parse as UTC and then switch to local mode before formatting:

    moment.utc(param).local().format('MMMM Do YYYY h:mm a')
    

  • 这篇关于如何使用 JavaScript 中的 moment 将 GMT 转换为本地时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆