I have a date string with me in the format – “20202” [“yyyyQ”]. Is there a way to get the corresponding quarter of previous year ?
ex- for 20202 , it should be 20192
Advertisement
Answer
An alternative to the other answers is using my lib Time4J and its class CalendarQuarter. Example:
String input = "20202";
ChronoFormatter<CalendarQuarter> f =
ChronoFormatter.ofPattern(
"yyyyQ",
PatternType.CLDR,
Locale.ENGLISH,
CalendarQuarter.chronology());
CalendarQuarter cq = f.parse(input);
CalendarQuarter quarterInPreviousYear = cq.minus(Years.ONE);
System.out.println(quarterInPreviousYear); // 2019-Q2
Two main advantages of this solution are:
- Calendar quarters are also intervals so it is easy to iterate over them daily.
- Internationalization is supported for more than 90 languages, even style-based.
Interval example:
for (PlainDate date : quarterInPreviousYear) {
System.out.println(date);
}
Output:
> 2019-04-01 > 2019-04-02 > 2019-04-03 > ...
Printing example in Danish:
ChronoFormatter<CalendarQuarter> printer =
ChronoFormatter.ofPattern(
"QQQQ y",
PatternType.CLDR,
new Locale("da"),
CalendarQuarter.chronology());
System.out.println(printer.print(quarterInPreviousYear)); // 2. kvartal 2019