Java的时间获得月份的第一天和最后一天

每日一经

每天收集一个java日常能用到的解决问题的方法,以后方便查阅。

实现

java8环境,有两个类 Temporal和TemporalAdjuster。提供了一些方法:
获取时间:

LocalDate (date without a time zone)
LocalTime (time without a time zone)
LocalDateTime (date-time without a time zone)

获取第一天和最后一天

firstDayOfMonth() (return the first day of the current month)
lastDayOfMonth() (return the last day of the current month)
firstDayOfNextMonth() (return the first day of the next month)
firstDayOfNextYear() (return the first day of the next year)

具体代码实例
1 初始化日期

LocalDate date = LocalDate.of(2021, Month.FEBRUARY, 27);

2 获取对应日期月份第一天

// 2021-02-01
LocalDate firstDayOfFeb = date.with(TemporalAdjusters.firstDayOfMonth());

3 获取对应日期月份最后一天

// 2021-02-28
LocalDate lastDayOfFeb = date.with(TemporalAdjusters.lastDayOfMonth());
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容