1 获取当前的年月日
const getCurrentDay = function () {
const date_ = new Date()
const year = date_.getFullYear()
const month = date_.getMonth() + 1
const day = date_.getDate()
return year + '/' + month + '/' + day
}
// 获取当前的年月
const getCurrentMonth = function () {
const date_ = new Date()
const year = date_.getFullYear()
const month = date_.getMonth() + 1
return year + '-' + month
}
// 返回选择日期的前后某一天
const getDateCount = function(targetDate, countDay) {
const date_ = new Date(targetDate) // 选定日期
date_.setDate(date_.getDate() + countDay) // countDay:当前日期前后某一天
const y = date_.getFullYear()
const m = date_.getMonth() + 1
const d = date_.getDate()
return y + '/' + m + '/' + d
}
// 获取月第一天
const getMonthFirst = function (targetDate = '') {
let date_ = ''
targetDate ? date_ = new Date(targetDate) : date_ = new Date()
date_.setDate(1)
let month = parseInt(date_.getMonth() + 1)
let day = date_.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return date_.getFullYear() + '/' + month + '/' + day
}
// 获取当前月最后一天
const getCurrentMonthLast = function () {
const date_ = new Date()
let getCurrentMonth = date_.getMonth()
const nextMonth = ++getCurrentMonth
const nextMonthFirstDay = new Date(date_.getFullYear(), nextMonth, 1)
const oneDay = 1000 * 60 * 60 * 24
const lastTime = new Date(nextMonthFirstDay - oneDay)
let month = parseInt(lastTime.getMonth() + 1)
let day = lastTime.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return date_.getFullYear() + '-' + month + '-' + day
}
// 获取上月
const getLastMonth = function () {
const date_ = new Date()
let year = date_.getFullYear()
let month = date_.getMonth()
if (month === 0) {
month = 12
year = year - 1
}
if (month < 10) {
month = '0' + month
}
return year + '-' + month
}
// 获取月份范围
const getMonthRange = function () {
const end = new Date()
const start = new Date()
start.setMonth(start.getMonth() - 6)
return [getFormatUTC(start), getFormatUTC(end)]
}
// UTC格式转换
function getFormatUTC(originVal) {
const date = new Date(originVal)
const y = date.getFullYear()
const m = '0' + (date.getMonth() + 1)
// const d = '0' + date.getDate()
// const h = date.getHours()
// const mm = date.getMinutes()
// const s = date.getSeconds()
// return `${y}-${m.substring(m.length - 2, m.length)}-${d.substring(d.length - 2, d.length)} ${h}:${mm}:${s}` // 2021-09-14 19:36:10
// return `${y}-${m.substring(m.length - 2, m.length)}-${d.substring(d.length - 2, d.length)}` //2021-09-14
return `${y}-${m.substring(m.length - 2, m.length)}` // 2021-09-14
}
// 上月最后一天
const getLastMonthDay = function (targetDate) {
const date_ = new Date(targetDate) // 选择日期
let year = date_.getFullYear()
let month = date_.getMonth()
if (month === 0) {
month = 12
year = year - 1
}
if (month < 10) {
month = '0' + month
}
const day = new Date(year, month, 0)
// const startDate = year + '-' + month + '-01 00:00:00' //上个月第一天
return year + '-' + month + '-' + day.getDate() // 上个月最后一天
}