Java:自定义为当前日期添加1个月 [英] Java: Customize adding 1 month to the current date

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

问题描述

我已经阅读了,基本上我已经弄清楚,Calendar对象能够通过使用以下方式添加1个月的日期:

 日历cal = Calendar.getInstance(); 
cal.add(Calendar.MONTH,1);

虽然我不喜欢它的行为,每当日期在30或31.如果有我添加1个月到01/31/2012,输出成为02/29/2012。当我再增加一个月,它变成03/29/2012。



有没有办法我可以强迫02/29/2012自动成为03/01/2012?



基本上这就是我想要发生的事情:



默认日期:01/31/2012



添加1个月:03/01/2012



再加1个月:03/31/2012

解决方案

你所要求的是一些隐含的知识,如果开始日期是月份的最后一天,而你添加1个月,结果应该是下个月的最后一天。即财产最后一个月应该是粘性的。



这不是直接在Java的日历中直接提供,但一种可能的解决方案是使用 Calendar.getActualMaximum(Calendar.DAY_OF_MONTH)重新设置月份之后的日期。

 日历cal = ...; 
cal.add(Calendar.MONTH,1);
cal.set(Calendar.DAY_OF_MONTH,cal.getActualMaximum(Calendar.DAY_OF_MONTH));

您甚至可以将 GregorianCalendar 方法

  public Calendar endOfNextMonth(){...} 

封装操作。


I've read around and basically I've figured out that the Calendar object is capable of adding 1 month to a date specified by using something like:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);

Although I don't like its behavior whenever the date is on either the 30 or 31. If ever I add 1 month to 01/31/2012, the output becomes 02/29/2012. When I add 1 more month, it becomes 03/29/2012.

Is there anyway I can force 02/29/2012 to become 03/01/2012 automatically?

Basically this is what I want to happen:

Default date: 01/31/2012

Add 1 month: 03/01/2012

Add 1 more month: 03/31/2012

解决方案

What you are asking for is some implicit knowledge that if the starting date is the last day of the month, and you add 1 month, the result should be the last day of the following month. I.e. the property "last-day-of-month" should be sticky.

This is not directly available in Java's Calendar, but one possible solution is to use Calendar.getActualMaximum(Calendar.DAY_OF_MONTH) to reset the day after incrementing the month.

Calendar cal = ...;
cal.add(Calendar.MONTH,1);
cal.set(Calendar.DAY_OF_MONTH,cal.getActualMaximum(Calendar.DAY_OF_MONTH));

You could even subclass GregorianCalendar and add a method

public Calendar endOfNextMonth() { ... }

to encapsulate the operation.

这篇关于Java:自定义为当前日期添加1个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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