今天发现的一个比较好的函数
/* * @params date 日期 * @params type 日期 prev/current/next 昨天/今天/明天 * @params fmt 日期拼接符 */ 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() // 获取时间戳(毫秒级) /* day为1,则是,明天的时间戳 day为-1,则是,昨天的时间戳 day为-2,则是,前天的时间戳 */ 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 }