Reputation: 99
I have a table where I would like each row to be represented as a date along with some other columns to represent the characteristic of that particular date. So, basically I would be having 365 rows for a year. I need to write a batch job in Java, which I would trigger through a rest endpoint. I would pass a particular year to the controller (eg 2020). I would then want a method which would get me all 366 days (since 2020 is a leap year) for 2020 along with the days i.e. weekends (Sat/Sun) or weekdays (Mon-Fri).
I would later do a batch insert into DB of those 366 days.
Can someone help me write this utility method.
Upvotes: 2
Views: 106
Reputation: 18588
To receive a list of dates of a given year, you can create a method like the following one using 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;
}
You can use the result in order to extract information about each day (in a main
for example):
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));
}
}
The output will look like this (just some of the lines for brevity):
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
Upvotes: 3