js 在日期不满足的情况下就会自动加1个月,比如在当前时间为3月31号,传入1,1两个参数,预期结果为2月29日,但是结果输出了3月2日。就是如果不满就会溢出到下个月,后来看了api发现了setMonth有两个方法,另外一个是指定月份,指定某一天,就可以解决这个问题
我们先看看按天数去计算的代码,很简单
var d = new Date(); d.setMonth(d.getMonth() +1); alert(d.toLocaleString());
但是我们要求的是自然月,所以需要判断 是否2月 且是否是闰年 ,我们还需要另外一个方法去格式化时间 ,代码如下
//求自然月日期 function getMonthBeforeFormatAndDay(num, format, day) { var date = new Date(); date.setMonth(date.getMonth() + (num*1), 1); //读取日期自动会减一,所以要加一 var mo = date.getMonth() + 1; //小月 if (mo == 4 || mo == 6 || mo == 9 || mo == 11) { if (day > 30) { day = 30 } } //2月 else if (mo == 2) { if (isLeapYear(date.getFullYear())) { if (day > 29) { day = 29 } else { day = 28 } } if (day > 28) { day = 28 } } //大月 else { if (day > 31) { day = 31 } } retureValue = date.format('yyyy' + format + 'MM' + format + day); return retureValue; } //JS判断闰年代码 function isLeapYear(Year) { if (((Year % 4) == 0) && ((Year % 100) != 0) || ((Year % 400) == 0)) { return (true); } else { return (false); } } //日期格式化 Date.prototype.format = function (format) { var o = { "M+": this.getMonth() + 1, // month "d+": this.getDate(), // day "h+": this.getHours(), // hour "m+": this.getMinutes(), // minute "s+": this.getSeconds(), // second "q+": Math.floor((this.getMonth() + 3) / 3), // quarter "S": this.getMilliseconds() // millisecond } if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); return format; }
这样就大功告成啦,网上好像没有这方面的代码,希望能帮到需要求自然月的同学
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2012-11-30 C#过滤关键字
2010-11-30 Linq to sql 之 GroupBy