substracting days with Calendar does not decrement year?

in order to thank me an happy new year, my java code is making something really unexpected : It does not decrement year when substracting 11 days at current date of 06/01/2022.

Somebody knows why it does not return "2021-12-26" ???

Code :

DateFormat dateFormat = new SimpleDateFormat('YYYY-MM-dd');
Date dt = new Date();
println "current_date : " + dateFormat.format(dt);

Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, -11);
dt = c.getTime();
println "substracted_date : " + dateFormat.format(dt);

Console :

current_date : 2022-01-06
substracted_date : 2022-12-26

Upvotes: 0

Views: 140

Answers (3)

貓村幻影
貓村幻影

Reputation: 184

The date format YYYY is the pattern for week year, instead of yyyy is for year.

The week year is updated by the week. For example, 2021-12-26 is the start of the first week of 2022 instead of 2021, so it'll show 2022. But the year is updated by date, so it'll show 2021.

Therefore, just change YYYY to yyyy and it'll work fine.

DateFormat dateFormat = new SimpleDateFormat('yyyy-MM-dd');

Upvotes: 4

thank you @Nekomura

to not be annoyed next time, I took belt and braces with 2 assert in order to not been surprised if using wrong pattern ^^ :

/**
 * renvoie un timestamp Fr de la date du serveur
 * @param pattern (du type "dd-MM-yyyy" ou "HH:mm:ss")
 * @param day_to_add permet d'ajout/retrancher des jours à la date actuelle
 * @param hour_to_add permet d'ajout/retrancher des heures à la date actuelle
 * @return le timetstamp au format correspondant à @pattern
 */
@Keyword
public static String getServerTimestamp(String pattern, int day_to_add, int hour_to_add) {

    assert !pattern.contains("Y") : "ne pas utiliser pattern 'Y' mais 'y' (sinon on prend week year et ça marche pas bien) ; voir reference https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html"
    assert !pattern.contains("D") : "ne pas utiliser pattern 'D' mais 'd' (sinon on prend day in year et ça marche pas bien) ; voir reference https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html"
    
    Date dt = new Date();
    Calendar c = Calendar.getInstance();
    c.setTime(dt);
    if (day_to_add != null) {
        c.add(Calendar.DATE, day_to_add);
    }
    if (hour_to_add != null) {
        c.add(Calendar.HOUR, hour_to_add);
    }
    dt = c.getTime();
    DateFormat dateFormat = new SimpleDateFormat(pattern);
    return dateFormat.format(dt);
}

Upvotes: 0

Trups
Trups

Reputation: 73

Try using LocalDate from Java8

import java.time.LocalDate;
public class test {
    public static void main(String[] args) {

        LocalDate date = LocalDate.parse("2022-01-06");
        System.out.println("Date : "+date);

        LocalDate newDate = date.minusDays(11);
        System.out.println("New Date : "+newDate);
    }
}

This will give you output as below Date : 2022-01-06 New Date : 2021-12-26

Upvotes: 0

Related Questions