我正在寻找一个函数转换日期在一个时区到另一个。

它需要两个参数,

日期(格式为“2012/04/10 10:10:30 +0000”) 时区字符串("Asia/Jakarta")

时区字符串在http://en.wikipedia.org/wiki/Zone.tab中描述

有什么简单的方法吗?


当前回答

好了,找到了!

我使用的是timezone-js。这是代码:

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

其他回答

做起来很简单:

const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; console.log(时区); var d = new Date(); console.log (d。toLocaleString('en-US', {timeZone}));

如果你不想导入一些大的库,你可以使用Intl。DateTimeFormat将Date对象转换为不同的时区。

// Specifying timeZone is what causes the conversion, the rest is just formatting const options = { year: '2-digit', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', timeZone: 'Asia/Jakarta', timeZoneName: 'short' } const formatter = new Intl.DateTimeFormat('sv-SE', options) const startingDate = new Date("2012/04/10 10:10:30 +0000") const dateInNewTimezone = formatter.format(startingDate) console.log(dateInNewTimezone) // 12-04-10 17:10:30 GMT+7

补偿,夏令时,和过去的变化将为您照顾。

更新

还有一个新的时态工具,可以处理时区和其他事情。比如只有日期或时间。目前还处于试验阶段

这是为了取代旧的遗产日期

var isoDate = new Date().toJSON() // eg: '2022-11-18T13:56:09.697Z'
Temporal.Instant.from(isoDate).toZonedDateTimeISO('Europe/Stockholm')

如果你有一个时区偏移,你可以使用这个:

const timezoneDate = (timestamp: number, offsetInHours: number) => {
  const shiftedTimestam = timestamp + offsetInHours * 3600000;

  const shiftedDate = new Date(shiftedTimestam);

  return {
    date: shiftedDate.getUTCDate(),
    hours: shiftedDate.getUTCHours(),
    minutes: shiftedDate.getUTCMinutes(),
    // ...other UTC methods
  }
};

// Usage:
const newYorkDate = timezoneDate(Date.now(), -5);

console.log(
  `It is ${newYorkDate.hours}:${newYorkDate.minutes} in NYC`
);

无耻地窃取自: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();
   
    // get UTC time in msec
    var utc = d.getTime();
   
    // 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();
}

这个函数通过提供城市/国家的名称和偏移值来计算时区值

好了,找到了!

我使用的是timezone-js。这是代码:

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