转自 https://www.jianshu.com/p/282beb319eca
```
import moment from "moment/moment";
//使用方法 获取当前日期 并且转成特定的字符串
export const toYear = (moment(new Date()).format('YYYY'))
export const toMonth = (moment(new Date()).format('MM'))
export const toDay = (moment(new Date()).format('DD'))
//将时间戳转为时间
let date = new Date(timeStamp).toDateString()
let time = moment(date).format('MM-DD hh:mm')
//获取当月的天数
export const getDaysOfMonth = (year, month) => {
var day = new Date(year, month, 0)
var dayCount = day.getDate()
return dayCount
}
export default class DateUtil {
static formatDate(date,fmt){
var o = {
"M+": date.getMonth() + 1, //月份
"d+": date.getDate(), //日
"h+": date.getHours(), //小时
"m+": date.getMinutes(), //分
"s+": date.getSeconds(), //秒
"q+": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
static stringToDate(str){
str = str.replace(/-/g,'/')
let date = new Date(str)
// date.setDate(date.getDate() + 1)
return date
}
// 2.获取几天之前或几天之后的日期 传入date和天数
static getBeforeDayDate(date,day) {
let timestamp = date.getTime();
// 获取day天前的日期
return new Date(timestamp - day * 24 * 3600 * 1000);
}
static getAfterDayDate(date,day) {
let timestamp = date.getTime();
// 获取day天之后的日期
return new Date(timestamp + day * 24 * 3600 * 1000);
}
}
//获取当月的天数
const getDaysOfMonth = (year, month) => {
let day = new Date(year, month, 0)
let dayCount = day.getDate()
return dayCount
}
//获取是当月第一天是周几
const getFirstDay = (year, month) => {
let day = new Date(year, month - 1)
let dayCount = day.getDay()
if (dayCount == 0) {
dayCount = 7
}
return dayCount
}
// 获取今天0点时间
import dayjs from 'dayjs'; // 引入时间组件
dayjs().startOf('day') // 当天0点时间
dayjs().endOf('day') // 当天24点时间
new Date(dayjs().startOf('day') - 24*60*60*1000) // 从前一天0点到当前时间
```