クイックリファレンス

Moment.js チートシート

Moment.js の包括的リファレンス:日付パース、フォーマットトークン一覧、日時加減算操作、ローカライズ書式、最新の代替ライブラリ。

· 公開日

Moment.js は、JavaScript で日付の解析、検証、操作、書式設定を行うための長年広く使われてきたライブラリです。

日時のパース (解析) と生成

// 現在の日時インスタンスを生成
const now = moment();

// フォーマット文字列を指定してパース
const m = moment('2026-10-25', 'YYYY-MM-DD');

// Unix タイムスタンプからパース (秒単位 vs ミリ秒単位)
moment.unix(1730000000); // 秒単位から
moment(1730000000000);   // ミリ秒単位から

// 日時の妥当性チェック
m.isValid(); // -> true

フォーマットトークン

m.format();                  // "2026-10-25T00:00:00+08:00" (// ISO 8601 標準フォーマット)
m.format('dddd');            // "Sunday"
m.format('MMM Do YY');       // "Oct 25th 26"
m.fromNow();                 // "// 相対時間表示 (例: 3 hours ago)"
m.calendar();                // "// カレンダー形式表示"

日付トークン一覧表

トークン 出力例・範囲 説明
YYYY 2026 4-digit year
YY 26 2-digit year
MM 01..12 2-digit month
MMM Jan..Dec Short month name
MMMM January..December Full month name
DD 01..31 2-digit day of month
Do 1st..31st Day of month with ordinal
d 0..6 Day of week (0 is Sunday)
ddd Sun..Sat Short day of week
dddd Sunday..Saturday Full day of week
Q 1..4 Quarter of the year

時刻トークン一覧表

トークン 出力例・範囲 説明
HH 00..23 24-hour hour (2-digit)
H 0..23 24-hour hour (1-digit)
hh 01..12 12-hour hour (2-digit)
mm 00..59 Minute (2-digit)
ss 00..59 Second (2-digit)
SSS 000..999 Milliseconds (3-digit)
A AM / PM Uppercase meridiem
a am / pm Lowercase meridiem
Z +08:00 Difference from UTC

日時の操作と加減算

Moment オブジェクトは ミュータブル (可変) です。加減算などの操作はインスタンスを直接変更します:

// 加算と減算
moment().add(7, 'days');
moment().subtract(1, 'month');

// 単位の境界時刻にセット
moment().startOf('day');  // 本日の 00:00:00.000
moment().endOf('month');  // 月末の 23:59:59.999

// 意図しない変更を防ぐためのクローン複製
const original = moment();
const nextWeek = original.clone().add(7, 'days');

ローカライズ済みフォーマットプリセット

フォーマット 出力例
LT 8:30 PM
LTS 8:30:25 PM
L 10/25/2026
LL October 25, 2026
LLL October 25, 2026 8:30 PM
LLLL Sunday, October 25, 2026 8:30 PM

推奨される最新の代替ライブラリ

現在 Moment.js はメンテナンスモードです。新規開発では以下のモダンなライブラリが推奨されます:

  • date-fns: イミュータブルで tree-shaking に対応したモジュール式関数群。
  • Day.js: Moment と互換性のある 2KB の軽量代替ライブラリ。
  • Luxon: Moment 開発チームによる、標準 Intl API を活用したモダンライブラリ。
  • Native Intl.DateTimeFormat: 外部依存なしでモダンブラウザや Node.js に標準搭載された国際化 API。

関連リファレンス

関連テーマ