我正在关注 https://www.alex-arriaga.com/how-to-set-moment-js-timezone-when-creating-a-date/ 的示例,但没有得到我正在期待。我的 startDateAndTimeString 将时间设置为 08:00,我将时区设置为 CST 中的 Mexico_City。然后我正在尝试转换为 New_York (EST) 和 Los_Angeles (PST) 时间。
我希望如果开始时间是 08:00 CST,那么它将是 09:00 EST 和 06:00 PST,但我看到的是 05:00 PST 和 08:00 EST。在本地,我在美国东部时间,如果我没有将开始时间设置为 CST,那将是有意义的。我在 EST 时可以不把开始时间设置为 CST 吗?
var startDateAndTimeString = '2023-03-05 08:00:00';
// CST
var startDateAndTime = moment(startDateAndTimeString).tz('America/Mexico_City');
function formatDateToAnotherTimezone(anotherTimezone, startDateAndTime) {
return moment(startDateAndTime).tz(anotherTimezone).format('ha z');
}
var est = formatDateToAnotherTimezone('America/New_York',startDateAndTime);
var pst = formatDateToAnotherTimezone('America/Los_Angeles',startDateAndTime);
console.log(est)
console.log(pst)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>
为了方便起见,我在墨西哥时区打印出由
startDateAndTime
表示的 GMT 时间。
可以看到第一个
console.log
打印错了答案
但是当我们正确调用 moment.tz 时,第二个
console.log
打印出正确的答案。
后续调整使用
startDateAndTime
的正确值。
var startDateAndTimeString = '2023-03-05 08:00:00';
// CST
var wrongStartDateAndTime = moment(startDateAndTimeString).tz('America/Mexico_City');
console.log("wrongStartDateAndTime",wrongStartDateAndTime)
startDateAndTime = moment.tz(startDateAndTimeString,'America/Mexico_City');
console.log("When we instead use moment.tz correctly:")
console.log("startDateAndTime",startDateAndTime)
function formatDateToAnotherTimezone(anotherTimezone, startDateAndTime) {
return moment(startDateAndTime).tz(anotherTimezone).format('ha z');
}
var est = formatDateToAnotherTimezone('America/New_York', startDateAndTime);
var pst = formatDateToAnotherTimezone('America/Los_Angeles', startDateAndTime);
console.log(est)
console.log(pst)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>