使用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.