文章詳情頁
js獲取今天、昨天、明天的日期函數代碼
瀏覽:83日期:2022-06-09 18:19:15
今天發現的一個比較好的函數
/* * @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}$is2tiay` } 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}-$is2tiay`), 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 }
到此這篇關于js獲取今天、昨天、明天的日期函數代碼的文章就介紹到這了,更多相關js獲取明天的日期內容請搜索以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持!
標簽:
JavaScript
排行榜
