当月最后一天的Java工具类
需求要求:
根据年月(YYYY-MM格式),返回该月最后一天(YYYY-MM-dd),例如输入 2023-06,返回2023-06-31
以下是用于根据年月返回该月最后一天的Java工具类实现:
java
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
public class LastDayOfMonthFinder {
public static String getLastDayOfMonth(String yearMonth) {
try {
YearMonth ym = YearMonth.parse(yearMonth, DateTimeFormatter.ofPattern("yyyy-MM"));
LocalDate lastDayOfMonth = ym.atEndOfMonth();
return lastDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
String yearMonth = "2023-06";
String lastDay = getLastDayOfMonth(yearMonth);
if (lastDay != null) {
System.out.println("Last day of " + yearMonth + ": " + lastDay);
} else {
System.out.println("Invalid input or calculation error.");
}
}
}
在这个工具类中,我们使用YearMonth类来解析年月字符串,并通过atEndOfMonth()方法获取该月的最后一天。然后,我们使用DateTimeFormatter将最后一天的日期格式化为"yyyy-MM-dd"格式。请注意,在getLastDayOfMonth方法中,我捕获了通用的Exception来处理可能的解析和计算错误。你可以根据需要进一步优化错误处理部分。最后,示例的main方法演示了如何使用这个工具类来获取指定年月的最后一天。