あるタイムゾーンの日付を別のタイムゾーンに変換する関数を探しています。
2つのパラメータが必要です。
- 日付(「2012/04/10 10:10:30 +0000」の形式)
- タイムゾーン文字列(「アジア/ジャカルタ」)
タイムゾーンの文字列はhttp://en.wikipedia.org/wiki/Zone.tabで説明されています
これを行う簡単な方法はありますか?
あるタイムゾーンの日付を別のタイムゾーンに変換する関数を探しています。
2つのパラメータが必要です。
タイムゾーンの文字列はhttp://en.wikipedia.org/wiki/Zone.tabで説明されています
これを行う簡単な方法はありますか?
これがワンライナーです:
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リファレンスです。
注意:上記の関数は、en-US
ロケールでフォーマットされた日付の文字列であるtoLocaleString結果の解析に依存することで機能します"4/20/2012, 5:10:30 PM"
。各ブラウザーは、フォーマットされた日付文字列をそのDateコンストラクターに受け入れない場合がありen-US
、予期しない結果を返す場合があります(夏時間を無視する場合があります)。
現在、すべての最新のブラウザはこの形式を受け入れ、夏時間を正しく計算します。古いブラウザやエキゾチックなブラウザでは機能しない場合があります。
補足:最新のブラウザにtoLocaleDate関数があれば素晴らしいので、このハッキーな回避策を使用する必要はありません。
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: 'Asia/Jakarta' });
console.log(str);
/**
* 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
大きなライブラリをインポートしたくない場合は、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
オフセット、夏時間、および過去の変更が自動的に処理されます。
とった!
表示された日付=サーバーの日付を強制したかったので、ローカル設定(UTC)をマットにしませんでした。
私のサーバーはGMT-6 -> new Date().getTimezoneOffset()
=360
myTZO = 360;
myNewDate = new Date(myOldDateObj.getTime() + (60000*(myOldDateObj.getTimezoneOffset()-myTZO)));
alert(myNewDate);
toLocaleString()メソッドを使用してタイムゾーンを設定できます。
new Date().toLocaleString('en-US', { timeZone: 'Indian/Christmas' })
インドの場合、「Indian / Christmas」を使用できます。以下は、さまざまなタイムゾーンです。
"Antarctica/Davis",
"Asia/Bangkok",
"Asia/Hovd",
"Asia/Jakarta",
"Asia/Phnom_Penh",
"Asia/Pontianak",
"Asia/Saigon",
"Asia/Vientiane",
"Etc/GMT-7",
"Indian/Christmas"
変数を設定し、year
記号で区切り、さらにamonth
とday
時間をHH:mm:ssパターンで設定し、その後に文字列の最後(私の場合はタイムゾーンは)を付けます。次に、この文字列を日付コンストラクターの引数として使用します。-
T
+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 );
使用できる外部ライブラリに関して制限があることに注意してください。moment.jsとtimezone-jsは私にとってオプションではありませんでした。
私が持っているjs日付オブジェクトはUTCです。特定のタイムゾーン(私の場合は「アメリカ/シカゴ」)のこの日付から日付と時刻を取得する必要がありました。
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());
UTCは現在、「アメリカ/シカゴ」より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());
これが私のコードです、それは完全に機能しています、あなたは以下のデモを与えることで試すことができます:
$(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>
日付オブジェクトを任意のタイムゾーンに変換する簡単な方法はわかりませんが、ローカルタイムゾーンに変換する場合はDate.prototype.getTime()
、対応するミリ秒数に変換してから、元に戻すことができます。
date = new Date('2016-05-24T13:07:20');
date = new Date(date.getTime());
たとえば、あなたが私のようにオーストリアにいる場合(そして夏)の代わりに、date.getHours()
が戻ってきます。15
13
一部のブラウザでは、さまざまな日時関数が非標準の動作を示す可能性があることを読みました。最初にこれをテストしてください。Chromeで動作することを確認できます。
日付のタイムゾーンをインドに変換する場合にも、これを試すことができます。
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);
私は最近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」または機能するものであれば何でもかまいません。
最初の引数がロケールのタイムゾーンで、secondeがターゲットのタイムゾーンの場合、正しいオフセットを持つDateオブジェクトを返します。
このページからのリンクを含む多くのことを見て、私は瞬間のタイムゾーンを使用して、この素晴らしい記事を見つけました:
要約すると:
ユーザーのタイムゾーンを取得する
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
日付/時刻をLA時刻に変換する
moment.utc('2016-12-25 07:00').tz('America/Los_Angeles').format('ddd, Do MMMM YYYY, h:mma');
返品:2016年12月24日(土)午後11時
LA時間からロンドンに変換
moment.tz('2016-12-25 07:00', 'America/Los_Angeles').tz('Europe/London').format( 'ddd, Do MMMM YYYY, h:mma' );
返品:2016年12月25日(日)午後3時
https://www.npmjs.com/package/ctoc_timezoneを使用することもでき ます
それは非常に単純な実装とフォーマットのカスタマイズを持っています。
toTimeZoneでのフォーマットの変更:
CtoC.toTimeZone(new Date(),"EST","Do MMM YYYY hh:mm:ss #{EST}");
出力:
28th Feb 2013 19:00:00 EST
ドキュメントで複数の機能を調べることができます。
現在の時刻をそのタイムゾーンに変更するには、たとえば「アジア/テヘラン」などの目的のタイムゾーンを指定します。「アジア/ソウル」を使用しました。
以下のコードを使用できます。必要に応じてスタイルを変更してください。
HH:MM:SSではなくh:m:s形式にする場合は、「関数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(timeZone);
var d = new Date();
console.log(d.toLocaleString('en-US', { timeZone }));
これに使用できるtimezones.jsonというnpmモジュールがあります。これは基本的に、夏時間とオフセットに関する情報を含むオブジェクトを含む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
お役に立てば幸いです
java.time
java 8パッケージに精通している人、または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年代のテストケースを移植したことを考えると、おそらく非常に正確に機能します。
クロノ操作は難しいです。そのため、他の多くのライブラリはエッジケースでバグがあります。Moment.jsはタイムゾーンを正しく取得しているようですが、私が見た他のjsライブラリ(を含むtimezone-js
)は信頼できないようです。
モーメントタイムゾーンの使用に問題がありました。他の誰かが同じ問題に直面した場合に備えて、この回答を追加します。だから私は2018-06-14 13:51:00
私のから来る日付文字列を持っていますAPI
。私はこれがに保存されていることを知っていUTC
ますが、文字列はそれ自体を語っていません。
次の手順を実行して、この日付のタイムゾーンを瞬間タイムゾーンに知らせます。
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.
希望する国のタイムゾーンを設定するだけで、1分ごとにSetInteval()関数を使用して更新をHTMLで簡単に表示できます。関数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;
}
});
サーバーの問題があります。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"
これらすべての答えには少し冗長ですが、これは特定の1時間ごとのオフセットで現在の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'));
これは、ReactNativeApplicationで機能します。
import moment from 'moment-timezone'
function convertTZ(date, tzString) {
const formatedDate = moment(date).tz(tzString).format()
return formatedDate
}
export {convertTZ}
現在のタイムゾーンのタイムゾーンオフセット
date +%s -d '1 Jan 1970'
私のGMT+10タイムゾーン(オーストラリア)では、-36000が返されました
迅速で汚れた手動アワーチェンジャーとリターン:
return new Date(new Date().setHours(new Date().getHours()+3)).getHours()