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

它需要两个参数,

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

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

有什么简单的方法吗?


当前回答

这是为我工作在React本机应用程序。

import moment from 'moment-timezone'

function convertTZ(date, tzString) {
  const formatedDate = moment(date).tz(tzString).format()
  return formatedDate
}

export {convertTZ}

其他回答

服务器有问题,选择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"

无耻地窃取自: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();
}

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

大多数浏览器都支持带参数的toLocaleString函数,旧的浏览器通常会忽略这些参数。

const str = new Date()。toLocaleString('en-US', {timeZone: '亚洲/雅加达'}); console.log (str);

这对每个人都适用。您可以通过手动更改机器上的时间来测试不同的时区。这个函数将相应地进行调整。

 function getCurrentTime() {
     const d = new Date() //2022-07-22T16:27:21.322Z
     const t = d.getTime(); //d in milliseconds 1658507241322
     const offset = -d.getTimezoneOffset()/60 //current offset in hours -4
     const curretMilli = t + (offset * 3600000) //cuuret local time milliseconds need to convert offset to milliseconds
     return new Date(curretMilli) //converts current local time in milliseconds to a Date //2022-07-22T12:27:21.322Z
 }

时区当前时区的偏移量

date +%s -d '1 Jan 1970'

对于我所在的GMT+10时区(澳大利亚),它返回-36000