Issue
public boolean checkDates(String oldDate, String newDate){
java.util.Calendar oldCal = java.util.Calendar.getInstance();
java.util.Calendar newCal = java.util.Calendar.getInstance();
String[] oD = oldDate.split("-");
String[] nD = newDate.split("-");
oldCal.set(Integer.parseInt(oD[0]), Integer.parseInt(oD[1])-1, Integer.parseInt(oD[2]));
newCal.set(Integer.parseInt(nD[0]), Integer.parseInt(nD[1])-1, Integer.parseInt(nD[2]));
if(newCal.compareTo(oldCal) > 0){
return true;
}else {
return false;
}
That's the code I'm implementing with varied results for dates on the same day. Sometimes compareTo delivers a 1 sometimes a 0. An example print of the dates being compared:
oldCal Fri Nov 17 23:30:48 CST 2021
newCal Fri Nov 17 23:30:48 CST 2021
All of the times have been the same on both the 1 returns and the 0's.
Solution
tl;dr
Use java.time.LocalDate
class.
LocalDate
.parse( "2022-01-23" )
.isAfter(
LocalDate.of( 2030 , Month.DECEMBER , 31 )
)
Fractional second varies
To answer your question directly, as commented by D Blacksmith, you are probably seeing two different values for the fractional second because you call java.util.Calendar.getInstance()
twice, two different methods.
To look at the bigger picture, you are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. Never use Date
, Calendar
, SimpleDateFormat
, and such.
java.time
I presume you are trying to compare date-only string values in format of YYYY-MM-DD. If so, then your entire need for writing your checkDates
method is moot.
The format of YYYY-MM-DD is actually the standard format defined by ISO 8601 for textual data-exchange of date-time values. The java.time classes use the standard ISO 8601 formats by default when parsing/generating such strings.
LocalDate x = LocalDate.parse( "2022-01-23" ) ;
LocalDate y = LocalDate.of( 2030 , Month.DECEMBER , 31 ) ;
The LocalDate
class implements Comparable
, so they know how to sort themselves. And the class offers handy comparison methods: isBefore
, isEqual
, and isAfter
.
boolean isXAfterY = x.isAfter( y ) ;
Android
The java.time functionality is built into Android 26 and later.
For earlier Android, modern tooling brings over most of the java.time functionality via “API desugaring”. If that does not do the job, add the ThreeTenABP library to your project.
Answered By - Basil Bourque