在react中使用date-fns:
import sub_days from 'date-fns/sub_days';
import start_of_week from 'date-fns/start_of_week';
import end_of_week from 'date-fns/end_of_week';
import start_of_month from 'date-fns/start_of_month';
import end_of_month from 'date-fns/end_of_month';
const theMoment = new Date();
const today = +theMoment;
const yerterday = +sub_days(theMoment, 1);
const startOfWeek = +start_of_week(theMoment, { weekStartsOn: 1 });
const endOfWeek = +end_of_week(theMoment, { weekStartsOn: 1 });
const startOfMonth = +start_of_month(theMoment);
const endOfMonth = +end_of_month(theMoment);
不使用时间库:
let date = new Date()
let lastDay = new Date(date.getTime() - 24 * 60 * 60 * 1000) //昨天
let currentMonth = date.getMonth()
let nextMonth = ++currentMonth
let nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1)
let oneDay = 1000 * 60 * 60 * 24
//返回date是一周中的某一天
let week = date.getDay()
//返回date是一个月中的某一天
let month = date.getDate()
//减去的天数
let minusDay = week != 0 ? week - 1 : 6
//获得当前周的第一天
let currentWeekFirstDay = new Date(date.getTime() - oneDay * minusDay)
//获得当前周的最后一天
let currentWeekLastDay = new Date(currentWeekFirstDay.getTime() + oneDay * 6)