LoginSignup
6
3

More than 5 years have passed since last update.

JavaScriptで月末、月初を取得するなら「date-fns」が超簡単

Last updated at Posted at 2019-02-06

結論

めっちゃ簡単だった。

「date-fns」インストール

いずれの方法で「date-fns」を使用できます。

npm or yarn

npm install date-fns --save
#or
yarn add date-fns

cdn

<script src="http://cdn.date-fns.org/VERSION/date_fns.min.js"></script>

月末、月初を取得するサンプルコード

「date-fns」のメソッドを使用するためには、まずimportが必要です。
inportしたメソッドを使って変数に入れれば、後は煮るなり焼くなりできます。

import startOfMonth from 'date-fns/start_of_month';
import subMonths from 'date-fns/sub_months';
import subDays from 'date-fns/sub_days';

const today = new Date; //今日の日付を取得
const startDay = startOfMonth(today); //今月1日を取得
const lastMonthStartDay = subMonths(startDay, +1); //subMonthsで月に対して加減ができる
const lastMonthEndDay = subDays(startDay, +1); //subDaysで日に対して加減ができる

console.log(lastMonthStartDay); //先月の月初
console.log(lastMonthEndDay); //先月の月末

startDayまでは単純にメソッドを使うだけです。
subMonthssubDaysメソッドは、第二引数に加減を加えることで、月日を変更できます。

今月が2月だとしたら、上記のサンプルでのconsole.logは1月になります。

所感

date-pickerと併用すれば、日付を扱うアプリケーションで有効活用できそうです!

6
3
3

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
6
3