gpt4 book ai didi

java - 当前月份的开始和结束日期

转载 作者:IT老高 更新时间:2023-10-28 20:48:55 25 4
gpt4 key购买 nike

我需要 Java 中当月的开始日期和结束日期。当 JSP 页面加载当前月份时,它应该自动计算该月的开始和结束日期。它应该与年份和月份无关。即某个月有 31 天或 30 天或 28 天。这也应该满足闰年。你能帮我解决这个问题吗?

例如,如果我在列表框中选择月份 May,我需要开始日期为 1,结束日期为 31。

最佳答案

你去吧:

public Pair<Date, Date> getDateRange() {
Date begining, end;

{
Calendar calendar = getCalendarForNow();
calendar.set(Calendar.DAY_OF_MONTH,
calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
setTimeToBeginningOfDay(calendar);
begining = calendar.getTime();
}

{
Calendar calendar = getCalendarForNow();
calendar.set(Calendar.DAY_OF_MONTH,
calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
setTimeToEndofDay(calendar);
end = calendar.getTime();
}

return Pair.of(begining, end);
}

private static Calendar getCalendarForNow() {
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(new Date());
return calendar;
}

private static void setTimeToBeginningOfDay(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
}

private static void setTimeToEndofDay(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
}

PS:Pair 类只是两个值的对。

关于java - 当前月份的开始和结束日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3083781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com