如何在不更改时间的情况下使用moment.js更改时区? [英] How to change the timezone with moment.js without changing the time?

查看:1745
本文介绍了如何在不更改时间的情况下使用moment.js更改时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期选择器,它以dddd, MMMM DO YYYY, h:mm:ss a格式将本地时间返回给变量localTime.我可以选择更改<select>中的时区,其中包含moment.tz.names()中的时区名称.当时区更改时,我需要将localTime的时区更改为新时区而不更改时间.如何使用moment.js

I have a datepicker which returns local time in the format dddd, MMMM DO YYYY, h:mm:ss a to a variable localTime. I have an option to change the timezone from a <select> which contains timezone names from moment.tz.names(). When timezone changes, I need to change the timezone of localTime to new timezone without changing the time.How can I do this with moment.js

let timeString = "Wednesday, January 10th 2018, 9:10:19 pm";
let localTime = moment(timeString, 'dddd, MMMM DO YYYY, h:mm:ss a').format('YYYY-MM-DD HH:mm:ss ZZ');
let localTimeInUtc = moment(timeString, 'dddd, MMMM DO YYYY, h:mm:ss a').utc().format('YYYY-MM-DD HH:mm:ss ZZ');
let newTimezone = "EST";
let newTime = moment(timeString, 'dddd, MMMM DO YYYY, h:mm:ss a').tz(newTimezone).format('YYYY-MM-DD HH:mm:ss ZZ');
let newTimeInUtc = moment(timeString, 'dddd, MMMM DO YYYY, h:mm:ss a').tz(newTimezone).utc().format('YYYY-MM-DD HH:mm:ss ZZ');
console.log(localTime);
console.log(localTimeInUtc);
console.log(newTime);
console.log(newTimeInUtc);

localTimenewTime

推荐答案

根据文件

也许您正在以下代码中寻找format2.

Maybe you are looking for format2 in the following code.

format1-创建力矩并设置时区(不会更新偏移量). format2-使用给定的时区创建时刻.

format1 - creates moment and sets the time-zone (will not update the offset). format2 - creates the moment with the given timezone.

var date = moment().format("dddd, MMMM D YYYY, h:mm:ss a"), format = "dddd, MMMM D YYYY, h:mm:ss a", timezone = "America/New_York";
var format1 = moment(date,format).tz(timezone);
var format2 = moment.tz(date, format,timezone);
console.log(format1.format(format)+" -> "+format1.format());
console.log(format2.format(format)+" -> "+format2.format());

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data.min.js"></script>

请查看此 Github问题一次.

这篇关于如何在不更改时间的情况下使用moment.js更改时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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