1
0

date-fnsの便利な関数を紹介

Posted at

はじめに

date-fnsを使用する機会があり、便利だと思った関数を紹介します。
ほかにあれば随時追記していきたい...

add - 指定された日付に、指定された年、月、週、日、時、分、秒を加算する。

const result = add(new Date(2014, 8, 1, 10, 19, 50), {
  years: 2,
  months: 9,
  weeks: 1,
  days: 7,
  hours: 5,
  minutes: 9,
  seconds: 30,
})
//=> Thu Jun 15 2017 15:29:20

formatDistance - 与えられた日付間の距離を単語で返す。

const result = formatDistance(new Date(2014, 6, 2), new Date(2015, 0, 1))
//=> '6 months'

formatDistanceToNow - 指定された日付から現在までの距離を単語で返す。

// 今日が2015年1月1日だとすると、2014年7月2日までの距離は?
const result = formatDistanceToNow(
  new Date(2014, 6, 2)
)
//=> '6 months'

isAfter - 第一引数の日付は第二引数より後か

const result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11))
//=> true

isBefore - 第一引数の日付は第二引数より前か

const result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11))
//=> false

sub - 指定された日付から、指定された年、月、週、日、時、分、秒を減算する。

const result = sub(new Date(2017, 5, 15, 15, 29, 20), {
  years: 2,
  months: 9,
  weeks: 1,
  days: 7,
  hours: 5,
  minutes: 9,
  seconds: 30
})
//=> Mon Sep 1 2014 10:19:50

getTime - 指定した日付のミリ秒単位のタイムスタンプを取得します。

const result = getTime(new Date(2012, 1, 29, 11, 45, 5, 123))
//=> 1330515905123

eachDayOfInterval - 指定した時間間隔内の日付の配列を返します。

const result = eachDayOfInterval({
  start: new Date(2014, 9, 6),
  end: new Date(2014, 9, 10)
})
//=> [
//   Mon Oct 06 2014 00:00:00,
//   Tue Oct 07 2014 00:00:00,
//   Wed Oct 08 2014 00:00:00,
//   Thu Oct 09 2014 00:00:00,
//   Fri Oct 10 2014 00:00:00
// ]

getOverlappingDaysInIntervals - 2つの時間間隔が重なる日数を取得する。

getOverlappingDaysInIntervals(
  { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },
  { start: new Date(2014, 0, 17), end: new Date(2014, 0, 21) }
)
//=> 3

isWithinInterval - 指定された日付はインターバル内か(開始と終了を含む)

isWithinInterval(new Date(2014, 0, 3), {
  start: new Date(2014, 0, 1),
  end: new Date(2014, 0, 7)
})
//=> true

isToday - 指定された日付は今日か

const result = isToday(new Date(2024, 8, 25, 14, 0))
//=> true

nextSunday - 次の日曜日はいつか

const result = nextSunday(new Date(2020, 2, 22))
//=> Sun Mar 29 2020 00:00:00

他の曜日版もあります。

1
0
1

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
1
0