Js获取明天、指定日期、本月第一天和最后一天
一、获取日期
// 获取日期方法(date为当天日期,i为相隔天数,例如:获取明天日期,则将i=1传入)
getDate (date, i) {
if (date === undefined || date === null) {
date = new Date();
}
let month, day;
date.setTime(date.getTime() + i * 24 * 60 * 60 * 1000);
month = date.getMonth() + 1 < 10 ? '0' + parseInt(date.getMonth() + 1) : date.getMonth() + 1;
day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
let time = date.getFullYear() + "-" + month + "-" + day;
return time;
}
二、获取本月第一天和最后一天
/**
* 获取本月第一天和最后一天
*/
getMonthStartAndEndDate () {
let nowDate = new Date()
let nowYear = nowDate.getFullYear() // 当前年
let nowMonth = nowDate.getMonth() // 当前月(值为0~11)
let firstDate = new Date(nowYear, nowMonth, 1)
let lastDate = new Date(nowYear, (nowMonth + 1), 0)
let list = []
list[0] = this.initDateFormat(firstDate)
list[1] = this.initDateFormat(lastDate)
return list
},
/**
* 格式化时间数据
*/
initDateFormat (date) {
let month = date.getMonth() + 1 < 10 ? '0' + parseInt(date.getMonth() + 1) : date.getMonth() + 1
let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
return date.getFullYear() + '-' + month + '-' + day
},
三、获取指定月份的第一天和最后一天
/**
* 获取指定月份(格式:yyyy-MM)第一天和最后一天,例如:2022-06,2022-06-01 2022-06-30
*/
function getRequireMonthStartAndEndDate (month) {
let index = month.lastIndexOf('-')
let nowYear = parseInt(month.substr(0, index)) // 当前年
let nowMonth = parseInt(month.substr(index + 1)) - 1 // 当前月(值为0~11)
let firstDate = new Date(nowYear, nowMonth, 1)
let lastDate = new Date(nowYear, (nowMonth + 1), 0)
let list = []
list[0] = initDateFormat(firstDate)
list[1] = initDateFormat(lastDate)
console.log(nowYear, nowMonth, firstDate, lastDate, list[0], list[1])
return list
}
四、获取本年第一天到本月最后一天
/**
* 获取本年第一天和到本月最后一天
*/
function getYearStartAndMonthEndDate () {
let nowDate = new Date()
let nowYear = nowDate.getFullYear() // 当前年
let nowMonth = nowDate.getMonth() // 当前月(值为0~11)
let firstDate = new Date(nowYear, 0, 1)
let lastDate = new Date(nowYear, (nowMonth + 1), 0)
let list = []
list[0] = initDateFormat(firstDate)
list[1] = initDateFormat(lastDate)
return list
}
本文来自博客园,作者:爱吃糖的橘猫,转载请注明原文链接:https://www.cnblogs.com/sglblog/p/16026000.html