我正在寻找一个函数转换日期在一个时区到另一个。
它需要两个参数,
日期(格式为“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中描述
有什么简单的方法吗?
当前回答
我在使用瞬间时区时遇到了麻烦。我加上这个答案是为了让其他人面对同样的问题。所以我有一个日期字符串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.
其他回答
大多数浏览器都支持带参数的toLocaleString函数,旧的浏览器通常会忽略这些参数。
const str = new Date()。toLocaleString('en-US', {timeZone: '亚洲/雅加达'}); console.log (str);
如果你只需要转换时区,我已经上传了一个精简版的moment-timezone,只有最基本的功能。其~1KB +数据:
S.loadData({
"zones": [
"Europe/Paris|CET CEST|-10 -20|01010101010101010101010|1GNB0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0|11e6",
"Australia/Sydney|AEDT AEST|-b0 -a0|01010101010101010101010|1GQg0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0|40e5",
],
"links": [
"Europe/Paris|Europe/Madrid",
]
});
let d = new Date();
console.log(S.tz(d, "Europe/Madrid").toLocaleString());
console.log(S.tz(d, "Australia/Sydney").toLocaleString());
这是为我工作在React本机应用程序。
import moment from 'moment-timezone'
function convertTZ(date, tzString) {
const formatedDate = moment(date).tz(tzString).format()
return formatedDate
}
export {convertTZ}
环顾四周,包括这个页面的链接,我发现了这篇很棒的文章,使用moment timezone:
https://www.webniraj.com/2016/11/23/javascript-using-moment-js-to-display-dates-times-in-users-timezone/
总结一下:
获取用户的时区
var tz = moment.tz.guess();
console.info('Timezone: ' + tz);
返回时区:欧洲/伦敦
设置默认用户时区
moment.tz.setDefault(tz);
设置自定义时区
moment.tz.setDefault('America/Los_Angeles');
将日期/时间转换为本地时区,假设原始日期/时间为UTC
moment.utc('2016-12-25 07:00').tz(tz).format('ddd, Do MMMM YYYY, h:mma');
返回时间:2016年12月25日,星期日,上午7:00
将日期/时间转换为洛杉矶时间
moment.utc('2016-12-25 07:00').tz('America/Los_Angeles').format('ddd, Do MMMM YYYY, h:mma');
返回时间:2016年12月24日星期六晚上11:00
将洛杉矶时间转换为伦敦时间
moment.tz('2016-12-25 07:00', 'America/Los_Angeles').tz('Europe/London').format( 'ddd, Do MMMM YYYY, h:mma' );
返回时间:2016年12月25日,星期日,下午3:00
对于moment.js用户,现在可以使用moment-timezone。使用它,你的函数看起来像这样:
function toTimeZone(time, zone) {
var format = 'YYYY/MM/DD HH:mm:ss ZZ';
return moment(time, format).tz(zone).format(format);
}