我正在寻找一个函数转换日期在一个时区到另一个。
它需要两个参数,
日期(格式为“2012/04/10 10:10:30 +0000”) 时区字符串("Asia/Jakarta")
时区字符串在http://en.wikipedia.org/wiki/Zone.tab中描述
有什么简单的方法吗?
我正在寻找一个函数转换日期在一个时区到另一个。
它需要两个参数,
日期(格式为“2012/04/10 10:10:30 +0000”) 时区字符串("Asia/Jakarta")
时区字符串在http://en.wikipedia.org/wiki/Zone.tab中描述
有什么简单的方法吗?
当前回答
服务器有问题,选择gmt+0000标准时区,你可以在javascript中使用moment-timezone库来更改它
const moment = require("moment-timezone")
const dateNew = new Date()
const changeZone = moment(dateNew);
changeZone.tz("Asia/Karachi").format("ha z");
// here you can paste "your time zone string"
其他回答
我应该指出,我在可以使用的外部库方面受到了限制。moment.js和timezone-js不是我的选择。
我拥有的js日期对象是UTC。我需要在特定的时区(在我的例子中是“America/Chicago”)从这个日期获得日期和时间。
var currentUtcTime = new Date(); // This is in UTC
// Converts the UTC time to a locale specific format, including adjusting for timezone.
var currentDateTimeCentralTimeZone = new Date(currentUtcTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));
console.log('currentUtcTime: ' + currentUtcTime.toLocaleDateString());
console.log('currentUtcTime Hour: ' + currentUtcTime.getHours());
console.log('currentUtcTime Minute: ' + currentUtcTime.getMinutes());
console.log('currentDateTimeCentralTimeZone: ' + currentDateTimeCentralTimeZone.toLocaleDateString());
console.log('currentDateTimeCentralTimeZone Hour: ' + currentDateTimeCentralTimeZone.getHours());
console.log('currentDateTimeCentralTimeZone Minute: ' + currentDateTimeCentralTimeZone.getMinutes());
国际标准时间目前比“美国/芝加哥”早6小时。输出是:
currentUtcTime: 11/25/2016
currentUtcTime Hour: 16
currentUtcTime Minute: 15
currentDateTimeCentralTimeZone: 11/25/2016
currentDateTimeCentralTimeZone Hour: 10
currentDateTimeCentralTimeZone Minute: 15
得到它!
希望强制显示的日期=服务器日期,无论本地设置(UTC)。
我的服务器是GMT-6——> new Date().getTimezoneOffset() = 360
myTZO = 360;
myNewDate = new Date(myOldDateObj.getTime() + (60000*(myOldDateObj.getTimezoneOffset()-myTZO)));
alert(myNewDate);
快速和肮脏的手动换时和返回:
return new Date(new Date().setHours(new Date().getHours()+3)).getHours()
服务器有问题,选择gmt+0000标准时区,你可以在javascript中使用moment-timezone库来更改它
const moment = require("moment-timezone")
const dateNew = new Date()
const changeZone = moment(dateNew);
changeZone.tz("Asia/Karachi").format("ha z");
// here you can paste "your time zone string"
我在使用瞬间时区时遇到了麻烦。我加上这个答案是为了让其他人面对同样的问题。所以我有一个日期字符串2018-06-14 13:51:00来自我的API。我知道这是存储在UTC,但字符串本身并不说话。
我让moment timezone知道这个日期来自哪个时区:
let uTCDatetime = momentTz.tz("2018-06-14 13:51:00", "UTC").format();
// If your datetime is from any other timezone then add that instead of "UTC"
// this actually makes the date as : 2018-06-14T13:51:00Z
现在我想通过这样做将其转换为特定的时区:
let dateInMyTimeZone = momentTz.tz(uTCDatetime, "Asia/Kolkata").format("YYYY-MM-DD HH:mm:ss");
// now this results into: 2018-06-14 19:21:00, which is the corresponding date in my timezone.