今天发现的一个比较好的函数
function getDays(date, type, fmt) {
let currentDate = new Date(date)
let y = currentDate.getFullYear()
let m = currentDate.getMonth() + 1
let d = currentDate.getDate()
function dateFormat(date, fmt) {
let y = new Date(date).getFullYear()
let m = new Date(date).getMonth() + 1
let d = new Date(date).getDate()
return `${y}${fmt}${m}${fmt}${d}`
}
switch (type) {
case "prev":
if (d - 1 < 1) {
if (m - 1 < 1) {
y = y - 1
m = 12
} else {
m = m - 1
}
d = new Date(y, m, 0).getDate()
} else {
d = d - 1
}
break
case "current":
break
case "next":
if (d + 1 > new Date(y, m, 0).getDate()) {
if (m + 1 > 12) {
y = y + 1
m = 1
d = 1
} else {
m = m + 1
d = 1
}
} else {
d = d + 1
}
break;
default:
break;
}
return dateFormat(new Date(`${y}-${m}-${d}`), fmt)
}
console.log(getDays(new Date('2023-5-13'), "prev", "-"));
console.log(getDays(new Date('2023-5-30'), "next", "-"));
console.log(getDays(new Date('2023-5-31'), "next", "-"));
再补充一个js 日期 获取今天、昨天、明天的函数
function getDay(day){
var today = new Date()
// 获取时间戳(毫秒级)
var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day
// Date.setTime(时间戳):设置当前日期的时间
today.setTime(targetday_milliseconds)
console.log('today=', today) // today= Sun Mar 05 2023 16:14:56 GMT+0800 (中国标准时间)
var tYear = today.getFullYear() // 年
var tMonth = today.getMonth() // 月
var tDate = today.getDate() // 日
tMonth = this.doHandleMonth(tMonth + 1)
tDate = this.doHandleMonth(tDate)
console.log('返回年月日=', tYear + '-' + tMonth + '-' + tDate)
return tYear + '-' + tMonth + '-' + tDate
}
function doHandleMonth(month) {
var m = month
if (month.toString().length == 1) {
m = '0' + month
}
return m
}
到此这篇关于js获取今天、昨天、明天的日期函数代码的文章就介绍到这了,更多相关js获取明天的日期内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!