Suppose, today its 2019-10-31 then I want a code to be saved as 001 and increment the code by 1 if it is within the same year ie code generated for 2019-11-01 is 002. Now, if its 2020-01-01 or after then I want the code to be generated as 001 again.
I have made the following assumptions:
this is the method I have come up with
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public static int code(String dateStr) {
LocalDate date = LocalDate.parse(dateStr, formatter);
LocalDate today = LocalDate.now();
return today.getYear() == date.getYear() ? date.getDayOfYear() - today.getDayOfYear() + 1 : date.getDayOfYear() ;
}
test method
public static void main(String[] args) {
System.out.println("2019-10-31 -> " + code("2019-10-31"));
System.out.println("2019-11-01 -> " + code("2019-11-01"));
System.out.println("2019-12-31 -> " + code("2019-12-31"));
System.out.println("2020-01-01 -> " + code("2020-01-01"));
System.out.println("2020-12-31 -> " + code("2020-12-31"));
System.out.println("2021-01-01 -> " + code("2021-01-01"));
}
output
2019-10-31 -> 1
2019-11-01 -> 2
2019-12-31 -> 62
2020-01-01 -> 1
2020-12-31 -> 366
2021-01-01 -> 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.