I'm trying to compare two datetimes but I can't get it to work.
public void time () {
Calendar c11 = Calendar.getInstance ();
c11.add(Calendar.DAY_OF_YEAR, 0);
c11.set(Calendar.HOUR_OF_DAY, 9);
c11.set(Calendar.MINUTE, 0 );
c11.set(Calendar.SECOND, 0);
Calendar c12 = Calendar.getInstance ();
c12.add(Calendar.DAY_OF_YEAR, 0);
c12.set(Calendar.HOUR_OF_DAY, 9);
c12.set(Calendar.MINUTE, 0 );
c12.set(Calendar.SECOND, 0);
c11.getTime();
c12.getTime();
boolean k = c11.equals(c12);
if (k==true)
{
Toast.makeText(
getContext(),
"Wow these two times are the same!",
Toast.LENGTH_LONG).show();
}
}
}
The milliseconds of the 2 time values are different so the equality comparison is going to return false.
Why are you adding 0 days to both calendar instances? That doesn't do anything.
public void onDateSelected(DateTime dateSelected) {
DateTime currentDateTime = new DateTime();
try{
/* If you want to compare only date from DateTime object then,
you can use "yyyy-MM-dd" format and split the string from T like:
dateSelected.toString().split("T") and use str1[0] to parse */
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ");
String str1 = dateSelected.toString();
Date selectedDate = formatter.parse(str1);
String str2 = currentDateTime.toString();
Date currentDate = formatter.parse(str2);
if (selectedDate.compareTo(currentDate)<0)
{
System.out.println("current date is Greater than my selected date");
}
}catch (ParseException e1){
e1.printStackTrace();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With