首先介绍一些基本概念,如下:
const date = new Date()
const year = date.getFullYear()
const month = date.getMonth()
const day = date.getDate()
const oneDay = new Date(year, month, day)
new Date(2022, 4, 25)等价于new Date('2022-05-25')
再介绍一些基本方法,如下:
const date = new Date()
date.setDate(1)
new Date(year, month, 1)
date.setDate(0)
new Date(year, month, 0)
new Date(year, month, new Date(year, month, 0).getDate())
最后实现,如下:
const getNowMonthFirst = () => {
const date = new Date()
date.setDate(1)
return date
}
const getNowMonthLast = () => {
const date = new Date()
const enddate = new Date(date.getFullYear(), date.getMonth() + 1, 0)
return enddate
}
const getLastMonthFirst = () => {
const date = new Date()
const firstDate = new Date(date.getFullYear(), date.getMonth() - 1, 1);
return firstDate
}
const getLastMonthLast = () => {
const date = new Date()
const day = new Date(date.getFullYear(), date.getMonth(), 0).getDate()
const enddate = new Date(date.getFullYear(), date.getMonth() - 1, day)
return enddate
}
或者
const getLastMonthLast = () => {
const date = new Date()
const enddate = new Date(date.getFullYear(), date.getMonth(), 0)
return enddate
}
或者
const getLastMonthLast = () => {
const date = new Date()
date.setDate(0)
return date
}
const getMonthFirst = (date) => {
const stringDate = new Date(date)
const enddate = new Date(stringDate.getFullYear(), stringDate.getMonth(), 1)
return enddate
}
const getMonthLast = (date) => {
const stringDate = new Date(date)
const enddate = new Date(stringDate.getFullYear(), stringDate.getMonth() + 1, 0)
return enddate
}