在JavaScript中将日期转换为另一个时区

本文翻译自:Convert date to another timezone in JavaScript

I am looking for a function to convert date in one timezone to another. 我正在寻找将一个时区中的日期转换为另一个时区的函数。

It need two parameters, 它需要两个参数,

  • date (in format "2012/04/10 10:10:30 +0000") 日期(格式为“ 2012/04/10 10:10:30 +0000”)
  • timezone string ("Asia/Jakarta") 时区字符串(“亚洲/雅加达”)

The timezone string is described in http://en.wikipedia.org/wiki/Zone.tab 时区字符串在http://en.wikipedia.org/wiki/Zone.tab中进行了描述

Is there an easy way to do this? 是否有捷径可寻?


#1楼

参考:https://stackoom.com/question/GkiL/在JavaScript中将日期转换为另一个时区


#2楼

Stolen shamelessly from: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329 从以下网址无耻地被盗: http : //www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329

/** 
 * function to calculate local time
 * in a different city
 * given the city's UTC offset
 */
function calcTime(city, offset) {

    // create Date object for current location
    var d = new Date();

    // convert to msec
    // add local time zone offset
    // get UTC time in msec
    var utc = d.getTime() + (d.getTimezoneOffset() * 60000);

    // create new Date object for different city
    // using supplied offset
    var nd = new Date(utc + (3600000*offset));

    // return time as a string
    return "The local time in " + city + " is " + nd.toLocaleString();
}

this function is useful to calculate time zone value by providing name of a city/country and offset value 此功能可通过提供城市/国家/地区的名称和偏移值来计算时区值


#3楼

Okay, found it! 好吧,找到了!

I'm using timezone-js . 我正在使用timezone-js this is the code: 这是代码:

var dt = new timezoneJS.Date("2012/04/10 10:10:30 +0000", 'Europe/London');
dt.setTimezone("Asia/Jakarta");

console.debug(dt); //return formatted date-time in asia/jakarta

#4楼

For moment.js users, you can now use moment-timezone . 对于moment.js用户,您现在可以使用moment-timezone Using it, your function would look something like this: 使用它,您的函数将如下所示:

function toTimeZone(time, zone) {
    var format = 'YYYY/MM/DD HH:mm:ss ZZ';
    return moment(time, format).tz(zone).format(format);
}

#5楼

除Safari外,大多数桌面(非移动)浏览器都支持带参数的toLocaleString函数,较旧的浏览器通常会忽略该参数。

new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' })

#6楼

Got it ! 得到它了 !

Wanted to force the date shown = server date, no mattter the local settings (UTC). 想要强制显示的日期=服务器日期,不影响本地设置(UTC)。

My server is GMT-6 --> new Date().getTimezoneOffset() = 360. 我的服务器是GMT-6-> new Date()。getTimezoneOffset()= 360。

myTZO = 360;
myNewDate=new Date(myOldDateObj.getTime() + (60000*(myOldDateObj.getTimezoneOffset()-myTZO)));
alert(myNewDate);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值