I'm getting a bit stuck with date comparison in Java/Android
DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm");
Calendar now = Calendar.getInstance();
Calendar c;
c = Calendar.getInstance();
c.set(settings.getInt("year", 0), settings.getInt("month", 0), settings.getInt("day", 0), settings.getInt("hour", 0), settings.getInt("minute", 0));
views.setTextViewText(R.id.textView4, String.valueOf(c.getTime().before(now.getTime())));
views.setTextViewText(R.id.textView2, String.format("%s - %s", df.format(c.getTime()), df.format(now.getTime())));
int timeout = 0;
while( c.getTime().before(now.getTime()) )
{
c.add(Calendar.SECOND, 30);
c.add(Calendar.MINUTE, 12);
c.add(Calendar.HOUR_OF_DAY, 6);
isHigh = 1 - isHigh;
timeout++;
if( timeout >= 400 )
break;
}
views.setTextViewText(R.id.textView5, String.valueOf(c.getTime().before(now.getTime())));
views.setTextViewText(R.id.textView3, String.format("%s - %s", df.format(c.getTime()), df.format(now.getTime())));
The idea of this is it takes a starting date from saved settings, and adds 6:12:30 to the clock until it passes the current time.
However, my textboxes give me the following:
false : 09/07/12 04:20 - 11/08/12 00:00
false : 09/07/12 04:20 - 11/08/12 00:00
Why is 9th July 2012 returning false when calling "before(11th Aug 2012)"?
If I change the ".before" to ".after", I get this:
true : 09/07/12 04:20 - 11/08/12 00:00
true : 20/10/12 15:40 - 11/08/12 00:00
Which doesn't seem to make any sense.
Any ideas what I'm doing wrong? Thanks
I wonder whether it's because your "year" setting is 12 rather than 2012. Then you'd be comparing 09/07/2012 with 11/08/0012 - but you can't tell because of your date format.
For diagnostic purposes, change your format string to "dd/MM/yyyy HH:mm"
and try again.
Well, its working as expected in JDK with 12 as well as 2012.
DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm");
Calendar now = Calendar.getInstance();
Calendar c;
c = Calendar.getInstance();
c.set(12, 6, 9, 0, 0);
System.out.println(String.valueOf(c.getTime().before(now.getTime())));
System.out.println(String.format("%s - %s", df.format(c.getTime()), df.format(now.getTime())));
Output:- true 09/07/12 00:00 - 11/08/12 13:29
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