javascript实现日期按月份加减
原文:https://www.jb51.net/article/66132.htm
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8"> <title></title> <script> function dateToDate(date) { var sDate = new Date(); if (typeof date == 'object' && typeof new Date().getMonth == "function" ) { sDate = date; } else if (typeof date == "string") { var arr = date.split('-') if (arr.length == 3) { sDate = new Date(arr[0] + '-' + arr[1] + '-' + arr[2]); } } return sDate; } function addMonth(date, num) { num = parseInt(num); var sDate = dateToDate(date); var sYear = sDate.getFullYear(); var sMonth = sDate.getMonth() + 1; var sDay = sDate.getDate(); var eYear = sYear; var eMonth = sMonth + num; var eDay = sDay; while (eMonth > 12) { eYear++; eMonth -= 12; } var eDate = new Date(eYear, eMonth - 1, eDay); while (eDate.getMonth() != eMonth - 1) { eDay--; eDate = new Date(eYear, eMonth - 1, eDay); } return eDate; } function calcDate() { var d = document.getElementById('date').value; var n = document.getElementById('num').value; var eDate = addMonth(d, n); document.getElementById('result').innerHTML = eDate.getFullYear() + '-' + (eDate.getMonth() + 1) + '-' + eDate.getDate(); } </script> </head> <body> <input type="date" id="date" /> <input type="number" id="num" value="1" /> <input type="button" value="计算" onclick="calcDate()" /> <div id="result"></div> </body> </html>
分类:
前端
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本