Day.jsを試してみる
概要
Day.js を試してみます。
インストール
$ npm install dayjs
使い方
- 基本
const dayjs = require('dayjs') const day = dayjs('2021-08-17 15:00:00') dayjs().format('YYYY-MM-DD HH:mm:ss') dayjs().set('month', 5).month() dayjs().add('year', 3) dayjs().isBefore(dayjs().add(1, 'day'))
- 現在日時の取得
const current = dayjs()
- フォーマット
dayjs().format('YYYY-MM-DD') // 2021-08-17
※ 利用できるフォーマットの一覧は「 List of all available parsing tokens」を参照
- Dateオブジェクトから
dayjs(new Date(2021, 8, 17))
- バリデーション
dayjs().isValid() // true dayjs(null).isValid() // false
- 年月日の取得
dayjs().format('YYYY-MM-DD') // 2021-08-17 dayjs().year() // 2021 dayjs().month() // 7 (0-11) dayjs().date() // 17
- 時分秒の取得
dayjs().format('YYYY-MM-DD HH:mm:ss') // 2021-08-17 18:28:03 dayjs().hour() // 18 dayjs().minute() // 28 dayjs().second() // 3
- 日時の操作(加算 / 減算)
const current = dayjs() current.format('YYYY-MM-DD') // 2021-08-17 current.add(3, 'year').year() // 2024 current.add(2, 'month').month() // 9 current.add(3, 'day').date() // 20 current.subtract(1, 'year').year() // 2020 current.subtract(3, 'month').month() // 4 current.subtract(7, 'day').date() // 10 current.add(-7, 'day').date() // 10
※ 指定できる単位の一覧は「List of all available units」を参照
- 月初 / 月末、一日の開始 / 終了の取得
const current = dayjs() current.format('YYYY-MM-DD') // 2021-08-17 current.startOf('month').format('YYYY-MM-DD') // 2021-08-01 current.endOf('month').format('YYYY-MM-DD') // 2021-08-31 current.startOf('day').format('YYYY-MM-DD HH:mm:ss') // 2021-08-17 00:00:00 current.endOf('day').format('YYYY-MM-DD HH:mm:ss') // 2021-08-17 23:59:59
- 差分の取得
const d1 = dayjs('2021-08-17') const d2 = dayjs('2020-08-17') d1.diff(d2, 'year') // 1 d1.diff(d2, 'month') // 12 d1.diff(d2, 'day') // 365
- 日付の比較
// const d1 = dayjs('2021-08-17') const d3 = dayjs('2021-08-18') d1.isBefore(d3) // true d1.isBefore(d3, 'day') // true d1.isBefore(d3, 'month') // false d1.isBefore(d3, 'year') // false d1.isAfter(d3) // false
プラグインの利用
const utc = require('dayjs/plugin/utc') dayjs.extend(utc) dayjs().format('YYYY-MM-DD HH:mm:ss') // 2021-08-17 19:00:00 (ローカルタイム) dayjs.utc().format('YYYY-MM-DD HH:mm:ss') // 2021-08-17 10:00:00 (UTC) dayjs().utc().format('YYYY-MM-DD HH:mm:ss') // 2021-08-17 10:00:00 (UTCに変換) dayjs.utc().local().format('YYYY-MM-DD HH:mm:ss') // 2021-08-17 19:00:00 (ローカルタイムに変換) dayjs().isUTC() // false dayjs().utc().isUTC() // true
- 閏年の判定
const isLeapYear = require('dayjs/plugin/isLeapYear') dayjs.extend(isLeapYear) dayjs('2021-08-17').isLeapYear() // false dayjs('2000-08-17').isLeapYear() // true