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

它需要两个参数,

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

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

有什么简单的方法吗?


无耻地窃取自: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

对于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);
}

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

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


得到它!

希望强制显示的日期=服务器日期,无论本地设置(UTC)。

我的服务器是GMT-6——> new Date().getTimezoneOffset() = 360

myTZO = 360;
myNewDate = new Date(myOldDateObj.getTime() + (60000*(myOldDateObj.getTimezoneOffset()-myTZO)));
alert(myNewDate);

我不知道一个简单的方法来转换日期对象到任何时区,但如果你想把它转换到本地时区,你可以用date .prototype. gettime()转换到相应的毫秒数,然后再回来。

let date0 = new Date('2016-05-24T13:07:20'); let date1 = new Date(date0.getTime()); console.log(“$ {date0} \ n $ {date1} ');

例如,date.getHours()现在将返回15而不是13,如果你像我一样在奥地利(而且是夏天)。

我读到过,各种datetime函数在某些浏览器中可能会表现出非标准的行为,所以先测试一下。我可以确认它在Chrome中工作。


有一个npm模块叫做timezones。Json你可以使用它。它基本上由一个json文件和包含夏令时和偏移量信息的对象组成。

对于asia/jakarta,它可以返回这个对象:

{
  "value": "SE Asia Standard Time",
  "abbr": "SAST",
  "offset": 7,
  "isdst": false,
  "text": "(UTC+07:00) Bangkok, Hanoi, Jakarta",
  "utc": [
    "Antarctica/Davis",
    "Asia/Bangkok",
    "Asia/Hovd",
    "Asia/Jakarta",
    "Asia/Phnom_Penh",
    "Asia/Pontianak",
    "Asia/Saigon",
    "Asia/Vientiane",
    "Etc/GMT-7",
    "Indian/Christmas"
  ]
}

你可以在这里找到它:

https://github.com/dmfilipenko/timezones.json

https://www.npmjs.com/package/timezones.json

希望对大家有用


设置一个变量,用-符号分隔年、月和日,加上一个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 );

你也可以尝试将日期时区转换为印度:

var indianTimeZoneVal = new Date().toLocaleString('en-US', {timeZone: 'Asia/Kolkata'});
var indainDateObj = new Date(indianTimeZoneVal);
indainDateObj.setHours(indainDateObj.getHours() + 5);
indainDateObj.setMinutes(indainDateObj.getMinutes() + 30);
console.log(indainDateObj);

我应该指出,我在可以使用的外部库方面受到了限制。moment.js和timezone-js不是我的选择。

我拥有的js日期对象是UTC。我需要在特定的时区(在我的例子中是“America/Chicago”)从这个日期获得日期和时间。

 var currentUtcTime = new Date(); // This is in UTC

 // Converts the UTC time to a locale specific format, including adjusting for timezone.
 var currentDateTimeCentralTimeZone = new Date(currentUtcTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));

 console.log('currentUtcTime: ' + currentUtcTime.toLocaleDateString());
 console.log('currentUtcTime Hour: ' + currentUtcTime.getHours());
 console.log('currentUtcTime Minute: ' + currentUtcTime.getMinutes());
 console.log('currentDateTimeCentralTimeZone: ' +        currentDateTimeCentralTimeZone.toLocaleDateString());
 console.log('currentDateTimeCentralTimeZone Hour: ' + currentDateTimeCentralTimeZone.getHours());
 console.log('currentDateTimeCentralTimeZone Minute: ' + currentDateTimeCentralTimeZone.getMinutes());

国际标准时间目前比“美国/芝加哥”早6小时。输出是:

currentUtcTime: 11/25/2016
currentUtcTime Hour: 16
currentUtcTime Minute: 15

currentDateTimeCentralTimeZone: 11/25/2016
currentDateTimeCentralTimeZone Hour: 10
currentDateTimeCentralTimeZone Minute: 15

如果你只需要转换时区,我已经上传了一个精简版的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());

熟悉java 8的人java。Time包,或者joda-time可能会喜欢这个新产品:js-joda库。

安装

npm install js-joda js-joda-timezone --save

例子

<script src="node_modules/js-joda/dist/js-joda.js"></script>
<script src="node_modules/js-joda-timezone/dist/js-joda-timezone.js"></script>
<script>
var dateStr = '2012/04/10 10:10:30 +0000';
JSJoda.use(JSJodaTimezone);
var j = JSJoda;
// https://js-joda.github.io/js-joda/esdoc/class/src/format/DateTimeFormatter.js~DateTimeFormatter.html#static-method-of-pattern
var zonedDateTime = j.ZonedDateTime.parse(dateStr, j.DateTimeFormatter.ofPattern('yyyy/MM/dd HH:mm:ss xx'));
var adjustedZonedDateTime = zonedDateTime.withZoneSameInstant(j.ZoneId.of('America/New_York'));
console.log(zonedDateTime.toString(), '=>', adjustedZonedDateTime.toString());
// 2012-04-10T10:10:30Z => 2012-04-10T06:10:30-04:00[America/New_York]
</script>

在真正的java本质中,这是相当啰嗦的。但是,作为一个移植的java库,特别是考虑到他们移植了1800个左右的测试用例,它也可能非常准确地工作。

时间操作是很难的。这就是为什么许多其他库在边缘情况下存在bug。Moment.js的时区似乎是正确的,但我所见过的其他js库,包括时区-js,似乎不值得信赖。


时区当前时区的偏移量

date +%s -d '1 Jan 1970'

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


如果你不想导入一些大的库,你可以使用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')

我最近在Typescript中做了这个:

// fromTimezone example : Europe/Paris, toTimezone example: Europe/London
private calcTime( fromTimezone: string, toTimezone: string, dateFromTimezone: Date ): Date {
  const dateToGetOffset = new Date( 2018, 5, 1, 12 );

  const fromTimeString = dateToGetOffset.toLocaleTimeString( "en-UK", { timeZone: fromTimezone, hour12: false } );
  const toTimeString = dateToGetOffset.toLocaleTimeString( "en-UK", { timeZone: toTimezone, hour12: false } );

  const fromTimeHours: number = parseInt( fromTimeString.substr( 0, 2 ), 10 );
  const toTimeHours: number = parseInt( toTimeString.substr( 0, 2 ), 10 );

  const offset: number = fromTimeHours - toTimeHours;

  // convert to msec
  // add local time zone offset
  // get UTC time in msec
  const dateFromTimezoneUTC = Date.UTC( dateFromTimezone.getUTCFullYear(),
    dateFromTimezone.getUTCMonth(),
    dateFromTimezone.getUTCDate(),
    dateFromTimezone.getUTCHours(),
    dateFromTimezone.getUTCMinutes(),
    dateFromTimezone.getUTCSeconds(),
  );

  // create new Date object for different city
  // using supplied offset
  const dateUTC = new Date( dateFromTimezoneUTC + ( 3600000 * offset ) );

  // return time as a string
  return dateUTC;
}

我使用“en-UK”格式,因为它是一个简单的。可能是"en-US"之类的。

如果第一个参数是本地时区,第二个参数是目标时区,它将返回一个具有正确偏移量的Date对象。


我在使用瞬间时区时遇到了麻烦。我加上这个答案是为了让其他人面对同样的问题。所以我有一个日期字符串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.

你可以使用to toLocaleString()方法来设置时区。

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

对于印度,你可以使用“印度/圣诞节”,以下是不同的时区,

"Antarctica/Davis",
    "Asia/Bangkok",
    "Asia/Hovd",
    "Asia/Jakarta",
    "Asia/Phnom_Penh",
    "Asia/Pontianak",
    "Asia/Saigon",
    "Asia/Vientiane",
    "Etc/GMT-7",
    "Indian/Christmas"

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


这是我的代码,它工作得很完美,你可以试试下面的演示:

$(document).ready(function() { //EST setInterval( function() { var estTime = new Date(); var currentDateTimeCentralTimeZone = new Date(estTime.toLocaleString('en-US', { timeZone: 'America/Chicago' })); var seconds = currentDateTimeCentralTimeZone.getSeconds(); var minutes = currentDateTimeCentralTimeZone.getMinutes(); var hours = currentDateTimeCentralTimeZone.getHours()+1;//new Date().getHours(); var am_pm = currentDateTimeCentralTimeZone.getHours() >= 12 ? "PM" : "AM"; if (hours < 10){ hours = "0" + hours; } if (minutes < 10){ minutes = "0" + minutes; } if (seconds < 10){ seconds = "0" + seconds; } var mid='PM'; if(hours==0){ //At 00 hours we need to show 12 am hours=12; } else if(hours>12) { hours=hours%12; mid='AM'; } var x3 = hours+':'+minutes+':'+seconds +' '+am_pm // Add a leading zero to seconds value $("#sec").html(x3); },1000); }); <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <p class="date_time"><strong id="sec"></strong></p> </body> </html>


你也可以使用 https://www.npmjs.com/package/ctoc_timezone

它有很多简单的实现和格式定制。

更改toTimeZone格式:

中华奥。toTimeZone(new Date(),"EST","Do MMM YYYY hh:mm:ss #{EST}");

输出:

2013年2月28日19:00:00 EST

您可以在文档中探索多种功能。


下面是一行代码:

function convertTZ(date, tzString) { return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString})); } // usage: Asia/Jakarta is GMT+7 convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") // Tue Apr 20 2012 17:10:30 GMT+0700 (Western Indonesia Time) // Resulting value is regular Date() object const convertedDate = convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") convertedDate.getHours(); // 17 // Bonus: You can also put Date object to first arg const date = new Date() convertTZ(date, "Asia/Jakarta") // current date-time in jakarta.

这是MDN参考。

注意:上面的函数依赖于解析toLocaleString结果,这是一个以en-US语言环境格式化的日期字符串,例如。“4/20/2012,下午5:10:30”。每个浏览器可能不接受en-US格式的日期字符串到它的日期构造函数,它可能返回意想不到的结果(它可能忽略夏令时)。

目前所有现代浏览器都接受这种格式并正确计算夏令时,它可能不适用于旧浏览器和/或外来浏览器。

旁注:如果现代浏览器有tolocedate,那就太好了 函数,所以我们不需要使用这个俗套的方法。


快速和肮脏的手动换时和返回:

return new Date(new Date().setHours(new Date().getHours()+3)).getHours()

只需设置你想要的国家时区,你可以很容易地在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;
        }


    });

提供所需的时区,例如“Asia/德黑兰”,以将当前时间更改为该时区。我用了“亚洲/首尔”。

您可以使用以下代码。如果需要更改样式。

请记住,如果你想要h:m:s格式而不是HH:MM:SS,你必须删除“函数kcwcheckT(i)”。

function kcwcheckT(i) { if (i < 10) { i = "0" + i; } return i; } function kcwt() { var d = new Date().toLocaleString("en-US", {timeZone: "Asia/Seoul"}); d = new Date(d); var h = d.getHours(); var m = d.getMinutes(); var s = d.getSeconds(); h = kcwcheckT(h); m = kcwcheckT(m); s = kcwcheckT(s); document.getElementById("kcwcurtime").innerHTML = h + ":" + m + ":" + s; var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]; document.getElementById("kcwcurday").innerHTML = days[d.getDay()] } kcwt(); window.setInterval(kcwt, 1000); @import url('https://fonts.googleapis.com/css2?family=Nunito&display=swap'); .kcwsource {color:#040505;cursor: pointer;display:block;width: 100%;border: none;border-radius:5px;text-align:center;padding: 5px 10px 5px 10px;} .kcwsource p {font-family: 'Nunito', sans-serif;} .CurTbx {color:#040505;cursor: pointer;display:block;width: 100%;border: none;border-radius:5px;text-align:center;padding: 5px 10px 5px 10px;} .kcwcstyle {font-family: 'Nunito', sans-serif; font-size: 22px;display: inline-block;} .kcwcurstinf {font-family: 'Nunito', sans-serif; font-size: 18px;display: inline-block;margin: 0;} .kcwcurday {margin: 0;} .kcwcurst {margin: 0 10px 0 5px;} /*Using the css below you can make your style responsive!*/ @media (max-width: 600px){ .kcwcstyle {font-size: 14px;} .kcwcurstinf {font-size: 12px;} } <div class="kcwsource"><p>This Pen was originally developed for <a href="http://kocowafa.com" target="_blank">KOCOWAFA.com</a></p></div> <div class="CurTbx"><p class="kcwcurst kcwcstyle" id="kcwcurday"></p><p class="kcwcurst kcwcstyle" id="kcwcurtime"></p><p class="kcwcurstinf">(Seoul, Korea)</p></div>


做起来很简单:

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


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

所有这些答案都有点多余,但这对我来说是有效的,可以获得具有特定小时偏移量的当前Date对象。

function hourToMs(hour) { return hour * 60 * 1000 * 60; } function minToMs(min) { return min * 60 * 1000; } function getCurrentDateByOffset(offset) { // Get the current timezone in milliseconds to reset back to GMT aka +0 let timezoneOffset = minToMs((new Date()).getTimezoneOffset()); // get the desired offset in milliseconds, invert the value because javascript is dum let desiredOffset = hourToMs(offset * -1); return new Date(Date.now() + timezoneOffset - desiredOffset); } // -6 hours is central timezone console.log("The time is: " + getCurrentDateByOffset(-6));


使用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'));


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

import moment from 'moment-timezone'

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

export {convertTZ}

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

 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
 }

你可以使用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);

This is UTC date; converting UTC to IST timezone; let sampleArray = [ { date: "2022-12-22T19:16:26.803" }, { date: "2022-12-22T19:16:26.77" }, { date: "2022-12-22T19:16:26.737" }, { date: "2022-12-22T19:16:26.72" } ]; // Get all the results whose boolresult is 'true' // solution 1 sampleArray.map((element) => { let utcDate = new Date(element.date).getTime(); let dateIST = new Date(utcDate); dateIST.setHours(dateIST.getHours() + 5); dateIST.setMinutes(dateIST.getMinutes() + 30); element.date = dateIST; }); console.log("Result ==>>", sampleArray); // solution 2 sampleArray.map((element) => { element.date = new Date(element.date).toLocaleString("en-US", { timeZone: "Asia/Kolkata" }); }); console.log("Result 2==>>", sampleArray);


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

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`
);