//获得上月开始时间
export function getLastMonthStartDate(){
var now = new Date(); //当前日期
var nowYear = now.getYear(); //当前年
nowYear += (nowYear < 2000) ? 1900 : 0;
var lastMonthDate = new Date(); //上月日期
lastMonthDate.setDate(1);
lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
var lastMonth = lastMonthDate.getMonth();
var lastMonthStartDate = new Date(nowYear, lastMonth, 1);
return formatDate(lastMonthStartDate);
}
//获得上月结束时间
export function getLastMonthEndDate(){
var now = new Date(); //当前日期
var nowYear = now.getYear(); //当前年
nowYear += (nowYear < 2000) ? 1900 : 0;
var lastMonthDate = new Date(); //上月日期
lastMonthDate.setDate(1);
lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
var lastMonth = lastMonthDate.getMonth();
var lastMonthEndDate = new Date(nowYear, lastMonth, getMonthDays(lastMonth));
return formatDate(lastMonthEndDate);
}
function formatDate(date) {
var myyear = date.getFullYear();
var mymonth = date.getMonth() + 1;
var myweekday = date.getDate();
if (mymonth < 10) {
mymonth = "0" + mymonth;
}
if (myweekday < 10) {
myweekday = "0" + myweekday;
}
return (myyear + "-" + mymonth + "-" + myweekday);
}
//获得某月的天数
function getMonthDays(myMonth){
var now = new Date(); //当前日期
var nowYear = now.getYear(); //当前年
nowYear += (nowYear < 2000) ? 1900 : 0;
var monthStartDate = new Date(nowYear, myMonth, 1);
var monthEndDate = new Date(nowYear, myMonth + 1, 1);
var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
return days;
}
//获取当月最后一天日期
export function getLastDay (year, month){
var new_year = year; //取当前的年份
var new_month = month++;//取下一个月的第一天,方便计算(最后一天不固定)
if (month > 12) {
new_month -= 12; //月份减
new_year++; //年份增
}
var new_date = new Date(new_year, new_month, 1); //取当年当月中的第一天
return (new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate();//获取当月最后一天日期
}
//获取本月开始日期
export function getStartDate (monthVal) {
var month = monthVal.getMonth() + 1
var strDate = monthVal.getDate()
if (month >= 1 && month <= 9) {
month = '0' + month
}
if (strDate >= 0 && strDate <= 9) {
strDate = '0' + strDate
}
var currentdate = monthVal.getFullYear() + '-' + month + '-' + strDate
return currentdate
}
//获取本月结束日期
export function getEndDate (monthValLast){
var year1 = monthValLast.getFullYear()
var month1 = monthValLast.getMonth() + 1
if (month1 >= 1 && month1 <= 9) {
month1 = '0' + month1
}
var currentdate1 = year1 + '-' + month1 + '-' + getLastDay(year1, month1)
return currentdate1
}
vue 引入上面的Js文件所有方法:
import * as util form "@/views/utils/formatDate"
使用:
monthChange (val) {
this.startDate = util.getStartDate(val[0]);
this.endDate = util.getEndDate(val[1]);
}