我有一个表,我希望其中的每一行都表示为一个日期,以及一些其他列来表示该特定日期的特征。所以,基本上我一年会有 365 行。我需要用 Java 编写一个批处理作业,我将通过休息端点触发该作业。我会将特定年份传递给 Controller (例如 2020)。然后,我想要一种方法,它可以让我获得 2020 年的所有 366 天(因为 2020 年是闰年)以及周末(周六/周日)或工作日(周一至周五)。
我稍后会批量插入这 366 天的数据库。
有人可以帮我写这个实用方法吗?
最佳答案
要接收给定年份的日期列表,您可以使用 java.time
创建如下方法:
public static List<LocalDate> getDaysOfYear(int year) {
// initialize a list of LocalDate
List<LocalDate> yearDates = new ArrayList<>();
/*
* create a year object from the argument
* to reliably get the amount of days that year has
*/
Year thatYear = Year.of(year);
// then just add a LocalDate per day of that year to the list
for (int dayOfYear = 1; dayOfYear <= thatYear.length(); dayOfYear++) {
yearDates.add(LocalDate.ofYearDay(year, dayOfYear));
}
// and return the list
return yearDates;
}
您可以使用结果来提取每天的信息(例如在 main
中):
public static void main(String[] args) {
// receive the LocalDates of a given year
List<LocalDate> yearDates = getDaysOfYear(2020);
// define a locale for output (language, formats and so on)
Locale localeToBeUsed = Locale.US;
// then extract information about each date
for (LocalDate date : yearDates) {
// or extract the desired parts, like the day of week
DayOfWeek dayOfWeek = date.getDayOfWeek();
// the month
Month month = date.getMonth();
// the calendar week based on a locale (the one of your system here)
WeekFields weekFields = WeekFields.of(localeToBeUsed);
int calendarWeek = date.get(weekFields.weekOfWeekBasedYear());
// and print the concatenated information (formatted, depending on the locale)
System.out.println(date.format(DateTimeFormatter.ofPattern("uuuu-MM-dd",
localeToBeUsed))
+ ", " + dayOfWeek.getDisplayName(TextStyle.FULL, localeToBeUsed)
+ ", CW " + calendarWeek
+ ", " + month.getDisplayName(TextStyle.FULL, localeToBeUsed));
}
}
输出将如下所示(为了简洁起见,仅显示一些行):
2020-01-01, Wednesday, CW 1, January
...
2020-02-29, Saturday, CW 9, February
...
2020-05-08, Friday, CW 19, May
...
2020-12-31, Thursday, CW 1, December
关于java - 获取一年的日期的Util,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63372323/