简体   繁体   中英

How to check if a date is greater than New year's date?

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:

  1. for a date in this year - get the difference in days from today, starting with 1 for today
  2. for a date in next year (or after that) - return day of year, starting with 1 up to 366

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM