问题描述
我有一张表,希望将每一行都表示为一个日期,并希望将其他一些列表示为该特定日期的特征。因此,基本上我一年将有365行。我需要用Java编写一个批处理作业,该作业将通过其余端点触发。我将特定年份传递给控制器(例如2020年)。然后,我想要一种方法,该方法可以使我在2020年的所有366天(因为2020年是leap年)以及周末(周六/周日)或工作日(周一至周五)这几天。
稍后,我将批量插入这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,December