Javascript日期:下个月 [英] Javascript Date: next month

查看:128
本文介绍了Javascript日期:下个月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用JavaScript的Date作为项目,但是注意到我以前工作的代码不再正常工作。而不是如预期的那样生产2月,下面的代码生成3月。

I've been using Javascript's Date for a project, but noticed today that my code that previously worked is no longer working correctly. Instead of producing Feb as expected, the code below produces March.

我的代码看起来像这样:

My code looks something like this:

current = new Date();
current.setMonth(current.getMonth()+1); //If today is Jan, expect it to be Feb now

这段代码每天工作直到今天。这是一个Javascript错误,还是我这样做错了?

This code worked everyday up until today. Is this a Javascript bug or am I going about this the wrong way?

推荐答案

你可能会发现你的日期设置为2009年2月31日(如果今天是1月31日)和Javascript自动滚动到3月初。

You'll probably find you're setting the date to Feb 31, 2009 (if today is Jan 31) and Javascript automagically rolls that into the early part of March.

检查一个月的日期,我希望它是1,2或3.如果不一样像之前添加的一个月一样,回滚一天直到月份再次变化。

Check the day of the month, I'd expect it to be 1, 2 or 3. If it's not the same as before you added a month, roll back by one day until the month changes again.

这样,Jan的最后一天变成2月的最后一天

That way, the day "last day of Jan" becomes "last day of Feb".

编辑:

罗纳德根据您对其他答案的意见,您可能想指导清楚的边缘案例行为,例如当我尝试制作2月30日会发生什么或当我尝试制作2009/13/07(yyyy / mm / dd)时会发生什么)(最后一个可能仍然是一个问题对于我的解决方案,所以你应该测试它)。

Ronald, based on your comments to other answers, you might want to steer clear of edge-case behavior such as "what happens when I try to make Feb 30" or "what happens when I try to make 2009/13/07 (yyyy/mm/dd)" (that last one might still be a problem even for my solution, so you should test it).

相反,我会明确地编写可能性。既然你不在乎一个月的日子(你只是希望下个月的年份和月份是正确的),这样就足够了:

Instead, I would explicitly code for the possibilities. Since you don't care about the day of the month (you just want the year and month to be correct for next month), something like this should suffice:

var now = new Date();
if (now.getMonth() == 11) {
    var current = new Date(now.getFullYear() + 1, 0, 1);
} else {
    var current = new Date(now.getFullYear(), now.getMonth() + 1, 1);
}

这给你1月1日在12月的任何一天的第二年,任何其他日子的下个月的日子。更多的代码,我知道,但我已经厌倦了编码技巧的效率,更喜欢可读性,除非有明确的要求。

That gives you Jan 1 the following year for any day in December and the first day of the following month for any other day. More code, I know, but I've long since grown tired of coding tricks for efficiency, preferring readability unless there's a clear requirement to do otherwise.

这篇关于Javascript日期:下个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆