JS如何获取未来n天的时间(返回日期:yyyy-mm-dd,并且判断是否是今天和星期)
作者:毛三仙
开发中经常遇到获取时间的业务,将常用的方法做个笔记记录下,对JS如何获取未来n天的时间相关知识感兴趣的朋友一起看看吧
js获取未来n天的时间(返回日期:yyyy-mm-dd,并且判断是否是今天,和星期)
2024.02.02(今天)如果传入5则获取未来5天的时间数组
[ {date: "2024-02-02,"isToday: true,week: "星期五"}, {date: "2024-02-03,"isToday: false,week: "星期六"}, {date: "2024-02-04,"isToday: false,week: "星期日"}, {date: "2024-02-05,"isToday: false,week: "星期一"}, {date: "2024-02-06,"isToday: false,week: "星期二"}, ]
initPredictionTime(num) { // 获取今天的日期 let today = new Date(); // 定义星期的数组 let weekdays = [ "星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", ]; // 获取今天是一周中的第几天(星期几) this.predictionWeek = weekdays[today.getDay()]; // 今天及接下来一周的日期和星期几 const result = []; for (let i = 1; i <= num; i++) { const dateString = today.getFullYear() + "-" + (today.getMonth() + 1).toString().padStart(2, "0") + "-" + today.getDate().toString().padStart(2, "0"); const week = weekdays[today.getDay()]; result.push({ week, date: dateString }); today.setDate(today.getDate() + 1); } result.find(item => item.week === this.predictionWeek).isToday = true; return result; },
js获取近N天的日期,返回'YYYY-mm-dd'格式
开发中经常遇到获取时间的业务,将常用的方法做个笔记记录下。
<html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <script> function getRecentDay(day){ var today = new Date(); var targetday_milliseconds=today.getTime() + 1000*60*60*24*day; today.setTime(targetday_milliseconds); var tYear = today.getFullYear(); var tMonth = today.getMonth(); var tDate = today.getDate(); tMonth = doHandleMonth(tMonth + 1); tDate = doHandleMonth(tDate); return tYear+"-"+tMonth+"-"+tDate; } function doHandleMonth(month){ var m = month; if(month.toString().length == 1){ m = "0" + month; } return m; } console.log("半年前:"+getRecentDay(-180)); console.log("三月前:"+getRecentDay(-90)); console.log("一月前:"+getRecentDay(-30)); console.log("昨天:"+getRecentDay(-1)); console.log("今天:"+getRecentDay(0)); console.log("明天:"+getRecentDay(1)); console.log("后天:"+getRecentDay(2)); console.log("一月后:"+getRecentDay(30)); console.log("三月后:"+getRecentDay(90)); console.log("半年后:"+getRecentDay(180)); </script> </body> </html>
原文作者技术博客: https://www.jianshu.com/u/ac4daaeecdfe
到此这篇关于JS如何获取未来n天的时间(返回日期:yyyy-mm-dd,并且判断是否是今天和星期)的文章就介绍到这了,更多相关js获取n天的时间内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!