Java日历自动更正月份的日期?

发布于 2024-10-16 03:08:51 字数 563 浏览 2 评论 0原文

我想了解在设置日期时是否有任何最简单的方法来纠正日期的值。我的意思是:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

喵星人汪星人 2024-10-23 03:08:51
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, birthYear);
cal.set(Calendar.MONTH, birthMonth);
cal.set(Calendar.DAY_OF_MONTH, Math.min(birthDay, cal.getActualMaximum(Calendar.DAY_OF_MONTH)));
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, birthYear);
cal.set(Calendar.MONTH, birthMonth);
cal.set(Calendar.DAY_OF_MONTH, Math.min(birthDay, cal.getActualMaximum(Calendar.DAY_OF_MONTH)));
め可乐爱微笑 2024-10-23 03:08:51

使用 calendar.getActualMaximum(Calendar.DAY_OF_MONTH) 查找该月的最大日期

Use calendar.getActualMaximum(Calendar.DAY_OF_MONTH) to find the maximum day of the month

眼中杀气 2024-10-23 03:08:51

不行,目前这是唯一的办法。

当然,您可能希望使用 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 a SimpleDateFormat). This is the most close to a one-liner you can get if your input is a String.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文