简体   繁体   English

如何检查日期是否大于新年日期?

[英]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.假设今天是 2019 年 10 月 31 日,那么我希望将代码保存为 001,如果它在同一年内将代码加 1,即为 2019 年 11 月 1 日生成的代码是 002。现在,如果它的 2020- 01-01 或之后,我希望代码再次生成为 001。

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对于今年的某个日期 - 获取从今天开始的天数差异,从今天的 1 开始
  2. for a date in next year (or after that) - return day of year, starting with 1 up to 366对于明年(或之后)的日期 - 返回一年中的日期,从 1 开始到 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 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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