5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptライブラリ Luxonの基本的な使い方 

Posted at

はじめに

業務でLuxonを使用する機会がありました。
その過程で学んだLuxonの基本的な使い方をまとめます。

Luxonとは

Luxonは、日付や時刻を操作するJavaScriptライブラリです。
Moment.js(現在は非推奨だが、かつて業界標準だったJavaScriptの日時操作ライブラリ)の後継的なライブラリにあたります。

公式ページ↓

インストール方法

npm install luxon

Node.js

const { DateTime } = require("luxon");

ES6(ECMAScript2015)

import { DateTime } from "luxon";

使い方

便利なことに、Luxon公式ページにおいて、開発者ツールのコンソールでLuxonが使用できます。
インストールせず手軽に動作確認したい場合に使用できます。

image.png

DateTimeクラス

DateTimeはLuxonの最も重要なクラスです。
DateTimeクラスを使って、新しい日時オブジェクトを作成できます。

日時オブジェクトの取得

・現在時刻の取得

DateTime.now();

・ローカル日時を取得(PCのタイムゾーン基準の日時を取得)

現在のローカル日時

DateTime.local();

指定したローカル日時

DateTime.local(2024, 5, 10, 8, 30);

・オブジェクトから作成

DateTime.fromObject({day: 15, hour: 12, minute: 30 }, { zone: "Asia/Tokyo" });

・ISO 8601文字列から作成

DateTime.fromISO("2024-05-10T08:30:00") 

ISO 8601とは、日付と時刻の表記に関するISOの国際規格です。
ISO 8601 では、日付と時間をTで区切って “YYYYMMDDTHHmmss” のような形式で表します。

UTCの場合Zをつけ、その他のタイムゾーンの場合はプラス/マイナス記号で時差を表記します。

例) 2024年5月10日 8時30分(日本時間)
2024-05-10T08:30:00+09:00

日付の変換(フォーマット)

・toString:ISO 8601に似たLuxon独自の文字列に変換
主にデバッグやログの出力時に使用されます。

const now = DateTime.now();
console.log(now.toString()); //"2025-03-13T10:45:30.123+09:00"

・toISO:ISO 8601形式に変換
toStringと同様、ISO 8601形式に変換されますが、
toISOはオプションでミリ秒やタイムゾーンの有無が変更可能です。

const now = DateTime.now();
console.log(now.toISO()); //"2025-03-13T10:45:30.123+09:00"

・toLocaleString():ローカルの日時フォーマットで文字列に変換

const now = DateTime.now();
console.log(now.toLocaleString()); //例:"2025/03/13"

・toFormat:任意の形式に変換

const now = DateTime.now();
console.log(now.toFormat("yyyy-MM-dd HH:mm:ss")); //"2025-03-13 10:45:30"

最後に

日付操作ライブラリを使用するのは初めてだったので、「DateTimeオブジェクト」という概念を理解するのに時間がかかりました。
実際に手元で動かして中身を確認するということが初期段階の理解に大きく役立つと感じました。
わからないときは自分でやってみるということを今後も意識していきたいです。

最後までお読みいただきありがとうございました!

参考

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?