Should I use Calendar.compareTo() to compare dates?

后端 未结 6 1823
情话喂你
情话喂你 2021-02-07 08:36

Is it a valid way of comparing dates:

Calendar someCalendar1 = Calendar.getInstance(); // current date/time
someCalendar1.add(Calendar.DATE, -14);

Calendar some         


        
6条回答
  •  南方客
    南方客 (楼主)
    2021-02-07 09:22

    It’s an old question now. For it to be helpful to the readers of today and tomorrow it needs a modern answer. That’s what I am providing here.

    java.time

        LocalDate someDate1 = LocalDate.now(ZoneId.of("Africa/Lusaka"))
                .minusDays(14);
        LocalDate someDate2 = LocalDate.of(2019, Month.OCTOBER, 11);
    
        if (someDate2.isBefore(someDate1)) {
            System.out.println("" + someDate2 + " is before " + someDate1);
        }
    

    When I ran this code today, the output was:

    2019-10-11 is before 2019-10-13

    While it was valid to use Calendar in 2009, the class was always poorly designed and is now long outdated. I certainly recommend that no one uses it anymore. Instead use java.time, the modern Java date and time API.

    Link: Oracle tutorial: Date Time explaining how to use java.time.

提交回复
热议问题