vad*_*sov 619 javascript momentjs
使用Moment.js我无法将正确的时刻对象转换为带时区的日期对象.我无法得到正确的日期.
例:
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())
Cha*_*rew 1116
使用此选项将矩形对象转换为日期对象:
来自http://momentjs.com/docs/#/displaying/as-javascript-date/
moment().toDate();
产量:
Tue Nov 04 2014 14:04:01 GMT-0600 (CST)
Mat*_*int 46
只要您使用所需区域的数据初始化了时间 - 时区,您的代码就会按预期工作.
您正确地将时刻转换为时区,这将反映在第二行输出中momentObj.format().
切换到UTC不仅会丢弃偏移量,而是会更改回UTC时区.如果您要这样做,则根本不需要原始.tz()呼叫.你可以做到moment.utc().
也许你只是想改变输出格式字符串?如果是这样,只需指定您想要的format方法参数:
momentObj.format("YYYY-MM-DD HH:mm:ss")
关于代码的最后几行 - 当你回到使用的Date对象时toDate(),你放弃了moment.js的行为并回到了JavaScript的行为.JavaScript Date对象将始终打印在其运行的计算机的本地时区中.没有什么时刻.js可以做到这一点.
其他几件小事:
虽然当下构造函数可以采用a Date,但通常最好不使用它.对于"现在",请勿使用moment(new Date()).相反,只需使用moment().两者都可以工作,但这是不必要的多余.如果要从字符串解析,请将该字符串直接传递给片刻.不要试图将其解析为Date第一个.你会发现瞬间的解析器更可靠.
时区就像MST7MDT是出于向后兼容的原因.它们来自POSIX风格的时区,其中只有少数属于TZDB数据.除非绝对必要,否则你应该使用诸如的密钥America/Denver.
小智 21
.toDate 对我来说并没有真正起作用,所以,这就是我所做的:
futureStartAtDate = new Date(moment().locale("en").add(1, 'd').format("MMM DD, YYYY HH:MM"))
希望这可以帮助
由于momentjs无法控制javascript日期对象,因此我找到了解决方法。
const currentTime = new Date();    
const convertTime = moment(currentTime).tz(timezone).format("YYYY-MM-DD HH:mm:ss");
const convertTimeObject = new Date(convertTime);这将为您提供一个带有转换时间的javascript date对象
这个问题有点晦涩。我会尽力解释这一点。首先,您应该了解如何使用moment-timezone。根据这里的答案 TypeError: moment().tz is not a function,您必须从moment-timezone导入 moment而不是默认 moment(当然,您必须先 npm install moment-timezone !)。为清楚起见,
const moment=require('moment-timezone')//import from moment-timezone
现在为了使用时区功能,请使用moment.tz("date_string/moment()","time_zone")(访问https://momentjs.com/timezone/了解更多详情)。此函数将返回具有特定时区的时刻对象。为清楚起见,
var newYork= moment.tz("2014-06-01 12:00", "America/New_York");/*this code will consider NewYork as the timezone.*/
现在,当您尝试使用 moment 的toDate()(ISO 8601 格式转换)转换 newYork(moment 对象)时,您将获得英国格林威治的时间。有关更多详细信息,请阅读有关 UTC 的这篇文章https://www.nhc.noaa.gov/aboututc.shtml。但是,如果您只想要这种格式的本地时间(纽约时间,根据此示例),只需将方法.utc(true)和arg true 添加到您的时刻对象。为清楚起见,
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()
简而言之,moment.tz 会考虑您指定的时区,并将您的当地时间与格林威治时间进行比较,以得出结果。我希望这是有用的。
let dateVar = moment('any date value');
let newDateVar = dateVar.utc().format();
漂亮干净!!!!
要转换任何日期,例如 utc:
moment( moment().utc().format( "YYYY-MM-DD HH:mm:ss" )).toDate()
| 归档时间: | 
 | 
| 查看次数: | 536809 次 | 
| 最近记录: |