JavaScriptの日付と時刻でつまずくところ
JavaScriptのDateは、
月は0から始まる
new Date(年, 月, 日)の
new Date(2026, 0, 31) // 2026年1月31日
new Date(2026, 11, 25) // 2026年12月25日曜日のgetDay()も、
はみ出した日は次の月へ繰り越す
ない
new Date(2026, 1, 30) // 2026年3月2日(2月30日はないので)
const d = new Date(2026, 0, 31);
d.setMonth(d.getMonth() + 1); // 2026年3月3日(「1か月後」のつもりが)1月31日のsetMonth()で
この
new Date(2026, 2, 0).getDate() // 28(2026年2月の日数)
new Date(2028, 2, 0).getDate() // 29(うるう年)文字列の書き方で、時刻が9時間ずれる
文字列から
| 書き方 | できる日時(日本時間) |
|---|---|
new Date('2026-11-21') | 2026年11月21日 9:00 |
new Date('2026-11-21T00:00') | 2026年11月21日 0:00 |
new Date('2026/11/21') | 2026年11月21日 0:00 |
日付だけの2026-11-21は、2026-11-21T00:00は、2026/11/21は
日本時間ではnew Date('2026-11-21')を
ないnew Date('2026-02-30')は、
toISOString()で日付が1日前になる
日付をtoISOString().slice(0, 10)とtoISOString()は
const t = new Date(2026, 10, 21, 8, 0); // 日本時間 11月21日 8:00
t.toISOString() // '2026-11-20T23:00:00.000Z'
t.toISOString().slice(0, 10) // '2026-11-20'(1日前)朝9時より
const ymd = (d) => new Intl.DateTimeFormat('en-CA', {
timeZone: 'Asia/Tokyo', year: 'numeric', month: '2-digit', day: '2-digit',
}).format(d);
ymd(t) // '2026-11-21' en-CA(カナダの
new Intl.DateTimeFormat('ja-JP', { timeZone: 'Asia/Tokyo', dateStyle: 'full', timeStyle: 'short' }).format(t)
// '2026年11月21日土曜日 8:00'
new Intl.DateTimeFormat('ja-JP-u-ca-japanese', { timeZone: 'Asia/Tokyo', era: 'long', year: 'numeric', month: 'long', day: 'numeric' }).format(t)
// '令和8年11月21日' この
| 書き方 | できた日時 |
|---|
いまの時刻
| 書き方 | 結果 |
|---|
1日が23時間の日もある
日本にはnew Date(2026, 2, 8, 2, 30)は
「2つの日時の差をDate.UTC()で
const days = (a, b) =>
(Date.UTC(b.getFullYear(), b.getMonth(), b.getDate())
- Date.UTC(a.getFullYear(), a.getMonth(), a.getDate())) / 86400000;
days(new Date(2026, 0, 1), new Date(2026, 11, 25)) // 358まとめ
- 月は
0から、 曜日は 日曜日が0。 - 文字列から
作るなら、 時刻と あわせて '2026-11-21T00:00'の形で 書く。 - 日付の
文字列を 作る ときは、 toISOString()ではなく、時間帯を 指定した Intl.DateTimeFormatを使う。 - 日数の
差は、 UTCの 0時に そろえてから 数える。
この