java - Java中下个月的最后日期
问题描述
如何在Java中获取下个月的最后一个日期?
背景:我有项目,用户只对订单感兴趣,应该在下个月底完成。所以我需要获取下个月的最后一个日期并与订单结束日期进行比较,如果订单结束日期小于下个月的最后一个日期,则意味着应该选择该订单。
我的解决方案是这样的,但不确定它是否是最好的:
public static boolean shouldCompleteByNextMonth(final Date endDate) {
final LocalDate now = LocalDate.now(); // Get current local date.
final LocalDate nextMonth = now.plusMonths(1); // Get next month.
final int daysInNextMonth = nextMonth.lengthOfMonth(); // Get the length of next month
final LocalDate lastLocalDateOfNextMonth = nextMonth.plusDays(daysInNextMonth - now.getDayOfMonth()); // Get the last Date of next month
// default time zone
final ZoneId defaultZoneId = ZoneId.systemDefault();
// convert last locale date to a Date
final Date lastDateOfNextMonth = Date.from(lastLocalDateOfNextMonth.atStartOfDay(defaultZoneId).toInstant());
// Compare with the given endDate, if last date of next month is after it, return true, else, return false.
return lastDateOfNextMonth.after(endDate);
}
解决方案
该类TemporalAdjusters
包含一些静态TemporalAdjuster
的,其中lastDayOfMonth()
,所以你可以做
LocalDate.now()
.plusMonth(1)
.with(TemporalAdjusters.lastDayOfMonth());
推荐阅读
- mysql - 我应该将每一个有用的值都插入数据库吗?
- node.js - Node.js 不会在 Chrome 上呈现,但会在带有 JWT 身份验证的 Postman 上呈现
- wordpress - 如何展示广告以仅向未登录用户展示广告?
- reactjs - 在 Chrome 中为 React 丢弃选项卡时状态丢失
- racket - Racket v7.0 中的#lang 问题
- javascript - JavaScript 中的表单提交按钮
- reactjs - 使用 AWS Cognito 和 React 仅 Facebook/Google 登录(无用户名/密码)
- c# - 使用数组进行统计(十进制)
- keyboard-shortcuts - Rider :转到下一个建议的键盘快捷键
- javascript - Onclick 进度条