使用Day.js取得月份起始日期

Ashley Hsueh
Feb 15, 2022

--

前言

  1. 欲解決的問題:想取得月份的第一天和最後一天
  2. 使用的套件 Day.js: Start of Time 、End of Time、Subtract 方法

實作

取得本月第一天日期和最後一天日期

本月份第一天的日期

const currentMonthStartDate = dayjs()
.startOf(‘month’)
.format(‘YYYY-MM-DD’)//轉換成字串的時間格式
console.log(currentMonthStartDate)// "2022-02-01"

本月份最後一天的日期

const currentMonthEndDate = dayjs()
.endOf(‘month’)
.format(‘YYYY-MM-DD’)
console.log(currentMonthEndDate)// "2022-02-28"

取得上個月第一天日期和上個月最後一天日期

上個月第一天的日期

const lastMonthStartDate = dayjs()
.subtract(1, 'month') //取得過去1個月的時間
.startOf('month')
.format('YYYY-MM-DD')
console.log(lastMonthStartDate)//"2022-01-01"

上個月最後一天的日期

const lastMonthEndDate = dayjs()
.subtract(1, 'month')
.endOf('month')
.format('YYYY-MM-DD')
console.log(lastMonthEndDate)//"2022-01-31"

取得下個月第一天日期和下個月最後一天日期

下個月第一天的日期

const nextMonthStartDate = dayjs()
.subtract(-1, 'month')
.startOf('month')
.format('YYYY-MM-DD')
console.log(nextMonthStartDate)//"2022-03-01"

下個月最後一天的日期

const  nextMonthEndDate = dayjs()
.subtract(-1, 'month')
.endOf('month')
.format('YYYY-MM-DD')
console.log(nextMonthEndDate)//"2022-03-31"

--

--

Ashley Hsueh
Ashley Hsueh

Written by Ashley Hsueh

社會新鮮人,記錄著學習的一切。

No responses yet