使用moment .js,我无法将正确的moment对象转换为带时区的date对象。我记不出准确的日期。
例子:
var oldDate = new Date(),
momentObj = moment(oldDate).tz("MST7MDT"),
newDate = momentObj.toDate();
console.log("start date " + oldDate)
console.log("Format from moment with offset " + momentObj.format())
console.log("Format from moment without offset " + momentObj.utc().format())
console.log("(Date object) Time with offset " + newDate)
console.log("(Date object) Time without offset "+ moment.utc(newDate).toDate())
只要使用所需区域的数据初始化了moment-timezone,代码就可以正常工作。
您正确地将时刻转换为时区,这反映在momentObj.format()输出的第二行中。
切换到UTC不仅会删除偏移量,还会更改回UTC时区。如果要这样做,则根本不需要原来的.tz()调用。你可以只执行moment.utc()。
也许您只是试图更改输出格式字符串?如果是这样,只需指定你想要格式化方法的参数:
momentObj.format("YYYY-MM-DD HH:mm:ss")
关于代码的最后几行-当你使用toDate()返回到Date对象时,你放弃了moment.js的行为,回到了JavaScript的行为。JavaScript Date对象将始终以运行它的计算机的本地时区打印。moment.js对此无能为力。
还有一些小事情:
While the moment constructor can take a Date, it is usually best to not use one. For "now", don't use moment(new Date()). Instead, just use moment(). Both will work but it's unnecessarily redundant. If you are parsing from a string, pass that string directly into moment. Don't try to parse it to a Date first. You will find moment's parser to be much more reliable.
Time Zones like MST7MDT are there for backwards compatibility reasons. They stem from POSIX style time zones, and only a few of them are in the TZDB data. Unless absolutely necessary, you should use a key such as America/Denver.
这个问题有点晦涩。我会尽力解释的。”首先,您应该了解如何使用moment-timezone。根据这里的答案TypeError: moment()。Tz不是一个函数,你必须从moment-timezone导入moment,而不是默认的moment(当然你必须先NPM安装moment-timezone !)为了清楚起见,
const moment=require('moment-timezone')//import from moment-timezone
现在,为了使用时区功能,请使用moment.tz("date_string/moment()","time_zone")(更多详细信息请访问https://momentjs.com/timezone/)。该函数将返回一个具有特定时区的moment对象。为了清楚起见,
var newYork= moment.tz("2014-06-01 12:00", "America/New_York");/*this code will consider NewYork as the timezone.*/
现在,当您尝试将newYork (moment对象)转换为moment的toDate() (ISO 8601格式转换)时,您将得到英国格林尼治时间。有关更多详细信息,请参阅关于UTC的文章https://www.nhc.noaa.gov/aboututc.shtml。然而,如果你只是想要这种格式的本地时间(根据这个例子,纽约时间),只需添加方法.utc(true),参数为true,到你的moment对象。为了清楚起见,
newYork.toDate()//will give you the Greenwich ,UK, time.
newYork.utc(true).toDate()//will give you the local time. according to the moment.tz method arg we specified above, it is 12:00.you can ofcourse change this by using moment()
简而言之,时刻。tz会考虑您指定的时区,并将您的本地时间与格林尼治时间进行比较,从而得到一个结果。我希望这对你有用。