Java日历自动更正月份的日期?
我想了解在设置日期时是否有任何最简单的方法来纠正日期的值。我的意思是:
int birthDay = 30;
int birthMonth = 1;
int birthYear = 1980;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, birthDay);
cal.set(Calendar.MONTH, birthMonth);
cal.set(Calendar.YEAR, birthYear);
二月没有30天。另一方面它有一个特殊的条件,1980年是二月有29天的一年。所以我必须得到正确的值“1980-February-29”。如果超出月份范围,应该取该月的最大天数。我怎样才能以最简单的方式做到这一点,如果我能找到不需要编写任何额外代码而不是使用 Calendar 类的方法的解决方案,那将是完美的。
编辑:我更改了 cal.set(Calendar.MONTH,birthMonth-1);到 cal.set(Calendar.MONTH,birthMonth);对此感到抱歉。
I want to learn that is there any easiest way to correct the values of day when setting it. I mean:
int birthDay = 30;
int birthMonth = 1;
int birthYear = 1980;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, birthDay);
cal.set(Calendar.MONTH, birthMonth);
cal.set(Calendar.YEAR, birthYear);
February doesn't have the day of 30. On the other hand it has a special condition, 1980 is a year that February is 29 days. So I have to get the corrected value as "1980-February-29". It should take the maximum day of that month if I exceed the range of month. How can I do it at simplest way and if I can find solution that doesn't need to write any extra code instead of using the methods of Calendar class it will be perfect.
EDIT: I changed cal.set(Calendar.MONTH, birthMonth-1); to cal.set(Calendar.MONTH, birthMonth); sorry for it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 calendar.getActualMaximum(Calendar.DAY_OF_MONTH) 查找该月的最大日期
Use calendar.getActualMaximum(Calendar.DAY_OF_MONTH) to find the maximum day of the month
不行,目前这是唯一的办法。
当然,您可能希望使用 java.text.DateFormat 对象(通常是 SimpleDateFormat)从字符串中解析日期。如果您的输入是
String
,那么这是最接近单行代码的情况。No, currently it's the only way.
Of course, you might want to parse a date from a String using a
java.text.DateFormat
object (typically aSimpleDateFormat
). This is the most close to a one-liner you can get if your input is aString
.