日历月实例关闭一 [英] Calendar Month Instance is off by one

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

问题描述

这是我的代码:

月是循环传递的。前0(因为我键入的是一月),然后是1,依此类推。下个月是二月,此循环将从该日期开始。 1、2等。

Month is passed in on a loop. First 0 (since it is January as I type), then 1, and so on. Next month when it is February, this loop will start from that date. 1, 2, etc.

    int thisMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;

    cal = Calendar.getInstance();
    df = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
    cal.set(Calendar.MONTH, month + thisMonth);

    String sMonth = df.format(cal.getTime());

在第一个循环中, sMonth 是三月2015。
在第二个循环中, sMonth 是2015年3月。
在第三个循环中, sMonth 是2015年4月。
在第四个循环中, sMonth 是2015年5月。
..依此类推

In the first loop, sMonth is March 2015. In the second loop, sMonth is March 2015. In the third loop, sMonth is April 2015. In the fourth loop, sMonth is May 2015. ..and so on

如您所见,第一个月不是预期的2月。我相信是1月29日,因此可能会有些原因,因为我们已经接近2月了。但是如果是这样,为什么会发生两次呢?

As you see, the first month is NOT February as expected. I believe it is January 29th so that may have some cause as we are so close to February. But if that is the case, why would this happen twice?

我知道,因为我没有使用unix时间戳,所以事情不准确,有没有办法计算这个

I know since I am not working with unix timestamps things aren't exact, is there away to calculate this where I can at least get accurate month ordering?

推荐答案

由于今天是30号,因此您可以获得当前日期(2015年) -01-30),然后增加月份以获取2015-02-30-自2月以来滚动至2015-03-02就没有30天了。

Since today is the 30th, you're getting the current date (2015-01-30), and incrementing the month to get 2015-02-30 - which "rolls over" to 2015-03-02 since February doesn't have 30 days.

避免此问题的一种方法是在更改月份之前将月份的日期设置为1。

One way to avoid this problem is to set the day-of-month to 1 before changing the month.

这篇关于日历月实例关闭一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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