如何从YearMonth日期获取月份的最后一天?(How to get the last day of month from a YearMonth date?)

编程入门 行业动态 更新时间:2024-10-27 17:24:15
如何从YearMonth日期获取月份的最后一天?(How to get the last day of month from a YearMonth date?)

我将把YearMonth日期转换为LocalDate,这将是该月的最后一天。 所以我需要使用toLocalDate(int i)方法。 如何使用yearMonth实例将该月的最后一天传递给该方法?

I am going to convert a YearMonth date to a LocalDate which is going to be the last day for that month. So I need to use the toLocalDate(int i) method. How can I get the last day of that month using the yearMonth instance to pass it to that method?

最满意答案

如果只是拥有一array数字,您可以使用以下内容以编程方式找出它:

if (month == 2 && year % 4 == 0) return 29; else if (month == 2) return 28; else { if (month > 7) month -= 1; if (month % 2 == 0) //Month number is even return 30; else return 31; }

所以要走过这个:

首先,你要检查是否是2月,这是闰年。 接下来你只是检查它是否是2月份。 之后,您正在查看月份是八月还是更晚,因为那是31天的月份开始。 如果是这种情况,您基本上可以从偶数更改月份数​​,反之亦然。 最后,您运行月份编号(编辑与否,取决于是否为8月或更晚),以查看它是偶数还是奇数,最终决定最后一天。

示例:2015年2月。 month = 2和year = 2015 。 month确实等于2但year % 4等于3 。 最终结果, return 28 。

示例2:2015年10月。 month = 10和year = 2015 。 month大于7,所以month = 9 。 month是奇数,所以最终结果, return 31 。

Finally I came up with this solution:

yearMonth.toLocalDate(yearMonth.plusMonths(1).toLocalDate(1).minusDays(1).getDayOfMonth())

I need to get the first day of the next month and then deducting 1 day from it using minusDays(1) method.

更多推荐

本文发布于:2023-07-29 21:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1319758.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   YearMonth   day   date   month

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!