momentjs toDate() - 时区被重置

coc*_*coa 10 javascript momentjs

我正在使用momentjs并将日期转换为不同的时区convertedDate = moment().utcOffset(timezone).format().这很好但是它是一个字符串,我需要将它转换为日期对象.

我已经尝试了new Date(convertedDate),moment().utcOffset(timezone).toDate()但是将当前时区作为日期对象返回.如何保留转换后的时区?

coc*_*coa 9

所以我不是很远.格式需要排除时区才能工作.这段代码终于解决了我需要它的方式.

convertedDate = new Date(moment().utcOffset('-4').format('YYYY-MM-DD HH:mm'));

  • 这不是一个好方法。它依赖于“ Date”对象的解析,并且基本上是关于输入与本地时间相差四个小时的。日期对象*不能*代表另一个时区。 (2认同)

Ame*_*san 6

根据时区获取带有时间的本机 Date 对象的更简洁方法moment如下:

convertedDate = moment.utc(moment.tz(timezone).format('YYYY-MM-DDTHH:mm:ss')).toDate()
Run Code Online (Sandbox Code Playgroud)

PS:假设两件事

  • 您已导入'moment''moment-timezone'
  • 的值代替偏移值timezone给出'Asia/Kolkata'