-1

i have to select a interval of time.

i have two timepickers on my app, i need to check if timepicker1 selected time is less than timepicker2 selected time. If not, i have to show a toast to told the user the error.

I also need to do this with two datepickers,not with times in that case, but with dates.

please can someone give me some code examples for do this?

NullPointerException
  • 36,107
  • 79
  • 222
  • 382

1 Answers1

2

You just need to compare the individual components of the date or time in the correct order. For time:

if (time1.getCurrentHour() < time2.getCurrentHour() || (time1.getCurrentHour() == time2.getCurrentHour() && time1.getCurrentMinute() < time1.getCurrentMinute())) {
  //time 1 is earlier.
}

You might need to add in a bit of complexity depending on if you are showing 24 hour time or not.

For dates, its the same, just compare first the year then the month then the day.

Cheryl Simon
  • 46,552
  • 15
  • 93
  • 82
  • that code is not correct, it will fail when hour is less but min is higher – NullPointerException Dec 13 '10 at 18:46
  • AndroidUser - that's not really that difficult. Wrap it in a method if you need to call it in a few different places. What are you expecting? – I82Much Dec 13 '10 at 19:10
  • You are right there was a bug there, sorry, I updated it. If you don't want to do it yourself, you could look at using joda time. Just construct a joda date or time object and you can use there comparison classes. See http://joda-time.sourceforge.net/index.html – Cheryl Simon Dec 13 '10 at 19:11