import moment from "moment";
// 时间
var now = new Date(); // 当前日期
var nowDayOfWeek = now.getDay(); // 今天本周的第几天
var nowDay = now.getDate(); // 当前日期
var nowMonth = now.getMonth(); // 当前月
var nowYear = now.getYear(); // 当前年
export function getTime(value){
nowYear += (nowYear < 2000) ? 1900 : 0;
//获得下周开始时间
var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 8);
//获得下周结束时间
var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek) + 8);
//获得下月开始时间
var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 8);
//获得下月结束时间
var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek) + 8);
if(value=="下周"){
return moment(weekStartDate).format("YYYY-MM-DD") + "," + moment(weekEndDate).format("YYYY-MM-DD");
}else if(value=="下月"){
return nextMonthFirstDay() + "," + nextMonthLastDay()
}
}
/*获取下个月的第一天*/
export function nextMonthFirstDay() {
var time = new Date();
var year = time.getFullYear();
var month = time.getMonth() + 2;
if (month > 12) {
month = month - 12;
year = year + 1;
}
var day = 1;
return year + '-' + month + '-' + day;
}
/*获取下个月的最后一天*/
export function nextMonthLastDay() {
var time = new Date();
var year = time.getFullYear();
var month = time.getMonth() + 2;
if (month > 12) {
month = month - 12;
year = year + 1;
}
var day = nextMonthDay(year, month);
return year + '-' + month + '-' + day;
}
//判断每月多少天
export function nextMonthDay(year, month) {
var day31 = [1, 3, 5, 7, 8, 10, 12];
var day30 = [4, 6, 9, 11];
if (day31.indexOf(month) > -1) {
return 31;
} else if (day30.indexOf(month) > -1) {
return 30;
} else {
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
}
}
//判断是否为闰年
export function isLeapYear(year) {
return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
}
以上代码封装为一个文件 再需要使用的文件中引入
直接传入value使用即可
代码中引用的moment是一个第三方插件,格式化日期的,也可手写格式化日期的函数。如下:
传入日期即可
getFormatDate: function (nowDate) {
var year = nowDate.getFullYear();
var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
var hour = nowDate.getHours()< 10 ? "0" + nowDate.getHours() : nowDate.getHours();
var minute = nowDate.getMinutes()< 10 ? "0" + nowDate.getMinutes() : nowDate.getMinutes();
var second = nowDate.getSeconds()< 10 ? "0" + nowDate.getSeconds() : nowDate.getSeconds();
return year + "-" + month + "-" + date+" "+hour+":"+minute+":"+second;
},