LoginSignup
58
35

More than 3 years have passed since last update.

Day.jsでよく使う機能の覚書

Posted at

JavaScriptの日付操作ライブラリであるDay.jsでよく利用する使い方について書き残しておきます。

公式ドキュメントが充実しているので、網羅的に知りたい方はそちらを見ていただいた方が早いでしょう。

基本

インストール

npm install dayjs --save

// or 

yarn add dayjs

import

import dayjs from 'dayjs';

const now  = dayjs() // 現在の日付情報を取得

日付情報の取得

例として現在の日時から各種情報を取得します。

月が0から始まる値で取得されることに注意しましょう。

dayjs().year() // 年
dayjs().month() // 月 (0~11)
dayjs().date() // 日
dayjs().day() // 曜日 0(日曜日)~6(土曜日)
dayjs().format('YYYY/MM/DD') // フォーマットして表示

日付情報の設定

dayjs().year(2020) // 日付情報の年を2020に更新
dayjs().month(8) // 日付情報の月を9月に更新
dayjs().date(12) // 日付情報の日を12日に更新
dayjs('2020-08-12') // 文字列をパースして更新

その他

日付情報の加算

dayjs().add(3, 'year') // 年に3を加算
dayjs().add(3, 'month') // 月に3を加算
dayjs().add(3, 'week') // 週に3を加算

日付情報の減算

dayjs().subtract(3, 'year') // 年に3を減算
dayjs().subtract(3, 'month') // 月に3を減算
dayjs().subtract(3, 'week') // 週に3を減算

unixtimeで出力

dayjs().unix()
dayjs().valueOf() // ミリ秒unixtime

unixtimeで日付情報の更新

dayjs.unix(1596836857)
dayjs(1596869215397)

Dateからの変換

const d = new Date(2020,8,12)
const day = dayjs(d)
58
35
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
58
35