Java – same day from this year

I need it on the same day this year

Example: now it is 2019, and the variable contains the value July 15, 2022, so I need to arrive on July 15, 2019 It applies to all dates, except February. It has an additional day in the year, and there is no such day this year. For example, February 29, 2020 will return to me the next day: March 1, 2019, but in this case, I need to return to the previous day: February 28, 2019 How do I adjust the logic so that it works this way?

public static java.util.Date getThisDateInThisYear(java.util.Date date) {
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(date);
    Date today = new Date();
    GregorianCalendar gcToday = new GregorianCalendar();
    gcToday.setTime(today);
    gc.set(GregorianCalendar.YEAR,gcToday.get(GregorianCalendar.YEAR));
    return gc.getTime();
  }

Solution

First calculate the year difference and add the result to the date

public Date getThisDateInThisYear(Date date) {
   Calendar c = Calendar.getInstance();
   int thisYear = c.get(Calendar.YEAR)
   c.setTime(date);

   int diff = thisYear  - c.get(Calendar.YEAR);
   c.add(Calendar.YEAR,diff);

   return c.getTime();

}

I tested 2016-02-29 and 2020-02-29, and both returned to 2019-02-28

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>