I would like to have a compareTo method that ignores the time portion of a java.util.Date. I guess there are a number of ways to solve this. What’s the simplest way?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Update: while Joda Time was a fine recommendation at the time, use the
java.timelibrary from Java 8+ instead where possible.My preference is to use Joda Time which makes this incredibly easy:
EDIT: As noted in comments, if you use
DateTimeComparator.getDateOnlyInstance()it’s even simpler 🙂(“Use Joda Time” is the basis of almost all SO questions which ask about
java.util.Dateorjava.util.Calendar. It’s a thoroughly superior API. If you’re doing anything significant with dates/times, you should really use it if you possibly can.)If you’re absolutely forced to use the built in API, you should create an instance of
Calendarwith the appropriate date and using the appropriate time zone. You could then set each field in each calendar out of hour, minute, second and millisecond to 0, and compare the resulting times. Definitely icky compared with the Joda solution though 🙂The time zone part is important:
java.util.Dateis always based on UTC. In most cases where I’ve been interested in a date, that’s been a date in a specific time zone. That on its own will force you to useCalendaror Joda Time (unless you want to account for the time zone yourself, which I don’t recommend.)Quick reference for android developers
Sample code (example)