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

它需要两个参数,

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

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

有什么简单的方法吗?


当前回答

你可以使用Intl。DateTimeFormat指定时区作为选项,它将日期或时间转换为所需的时区。

let timezone = "Asia/Jakarta";
let date = new Date("2012/04/10 10:10:30 +0000");
let formattedDate = new Intl.DateTimeFormat("en-US", { dateStyle: "long" , timeStyle: "short",  timeZone: timezone}).format(date);

其他回答

使用luxon库:

import { DateTime } from "luxon";

// Convert function:
const convertTz = (datetime, fromTz, toTz, format='yyyy-MM-dd HH:mm:ss') => {
  return DateTime.fromFormat(datetime, format, { zone: fromTz }).setZone(toTz).toFormat(format);
}

// Use it like this:
console.log(convertTz('2021-10-03 19:00:00', 'Europe/Lisbon', 'America/New_York'));

环顾四周,包括这个页面的链接,我发现了这篇很棒的文章,使用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

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

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

设置一个变量,用-符号分隔年、月和日,加上一个T和HH:mm:ss模式的时间,在字符串末尾加上+01:00(在我的例子中,时区是+1)。然后使用此字符串作为日期构造函数的参数。

// desired format: 2001-02-04T08:16:32+01:00
dateAndTime = year+"-"+month+"-"+day+"T"+hour+":"+minutes+":00+01:00";

var date = new Date(dateAndTime );

只需设置你想要的国家时区,你可以很容易地在html中显示它更新使用setinterval()函数后每一分钟。函数formatAMPM()管理12小时格式和AM/PM时间显示。

$(document).ready(function(){
        var pakTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Karachi"});
        pakTime = new Date(pakTime);

        var libyaTime = new Date().toLocaleString("en-US", {timeZone: "Africa/Tripoli"});
        libyaTime = new Date(libyaTime);



         document.getElementById("pak").innerHTML = "PAK  "+formatAMPM(pakTime);
         document.getElementById("ly").innerHTML = "LY   " +formatAMPM(libyaTime);

        setInterval(function(today) {
            var pakTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Karachi"});
            pakTime = new Date(pakTime);

            var libyaTime = new Date().toLocaleString("en-US", {timeZone: "Africa/Tripoli"});
            libyaTime = new Date(libyaTime);


           document.getElementById("pak").innerHTML = "PAK  "+formatAMPM(pakTime);
           document.getElementById("ly").innerHTML = "LY  " +formatAMPM(libyaTime);

        },10000);

         function formatAMPM(date) {
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var ampm = hours >= 12 ? 'pm' : 'am';
            hours = hours % 12;
            hours = hours ? hours : 12; // the hour '0' should be '12'
            minutes = minutes < 10 ? '0'+minutes : minutes;
            var strTime = hours + ':' + minutes + ' ' + ampm;
            return strTime;
        }


    });