Date と Timezone
ちょっとしたメモです。でてくるサンプルコードは JavaScript です。
- ISO 8601とは
- 日付と時刻の表記に関するISOの国際規格
2010-10-10T00:00:00.000+09:00
みたいなやつ- ISO 形式 (ISO 8601) の文字列判定 - ryotah’s blog
- 1888年以前は東京のオフセットは +09:18:59 なんだそうです
new Intl.DateTimeFormat('ja-JP', { dateStyle: 'long', timeStyle: 'long' }).format(new Date(-2587712400000)) // => "1888年1月1日 0:00:00 GMT+9" new Intl.DateTimeFormat('ja-JP', { dateStyle: 'long', timeStyle: 'long' }).format(new Date(-2587712400001)) // => "1888年1月1日 0:18:58 GMT+9:18:59"
- Date オブジェクトは関係演算子 (
==
とか>
とか) で比較可能- 比較演算子 - JavaScript | MDN
moment
やluxon
などの Date 系ライブラリで生成されたオブジェクトが関係演算子で比較できるのも、valueOf
を持っているから- https://moment.github.io/luxon/docs/manual/math.html#comparing-datetimes
DateTime implements #valueOf to return the epoch timestamp, so you can compare DateTimes with <, >, <=, and >=.
- 厳密等価演算子 (
===
) は型変換なしで比較をするので注意 (同時刻だとしてもtrue
にはならない)
- https://moment.github.io/luxon/docs/manual/math.html#comparing-datetimes
- IANA timezone name とは
America/Los_Angeles
,Asia/Tokyo
のようなタイムゾーンを表すことができる名前- https://www.iana.org/time-zones
The Time Zone Database (often called tz or zoneinfo) contains code and data that represent the history of local time for many representative locations around the globe
- https://ja.wikipedia.org/wiki/Tz_database
- IANA timezone と IE11
- IE 11 でも
Intl.DateTimeFormat
は利用できるが IANA timezone name には対応していない - http://kangax.github.io/compat-table/esintl/#test-DateTimeFormat_accepts_IANA_timezone_names
- (DateTimeFormat の詳細を開けて確認してください)
- IE 11 でも
- いつタイムゾーンを気にすべきか
import { DateTime, Settings } from "luxon"; Settings.defaultZoneName = 'Asia/Tokyo'; /** * 生成 */ console.log(DateTime.fromISO("2019-10-05T14:00:00").valueOf()); // => 1570251600000 console.log(DateTime.fromISO("2019-10-05T14:00:00", { zone: "America/Los_Angeles" }).valueOf()); // => 1570309200000 const tokyo = DateTime.fromISO("2019-10-05T14:00:00"); /** * 取得, 変更 */ console.log(tokyo.hour); // => 14 console.log(tokyo.setZone("America/Los_Angeles").hour); // =>22 console.log(tokyo.startOf('day')); // `startOf("day")` で「日」の開始に変更 console.log(tokyo.startOf('day').valueOf()); // => 2019-10-05T00:00:00.000+09:00 // => 1570201200000 console.log(tokyo.setZone("America/Los_Angeles").startOf('day')); console.log(tokyo.setZone("America/Los_Angeles").startOf('day').valueOf()); // => 2019-10-04T00:00:00.000-07:00 // => 1570172400000 /** * 表示 */ console.log(tokyo.toLocaleString(DateTime.DATETIME_SHORT)); // => 10/5/2019, 2:00 PM console.log(tokyo.setZone("America/Los_Angeles").toLocaleString(DateTime.DATETIME_SHORT)); // => 10/4/2019, 10:00 PM