In my code I need to find all my things that happened today. So I need to compare against dates from today at 00:00am (midnight early this morning) to 12:00pm (midnight tonight).
I know ...
Date today = new Date();
... gets me right now. And ...
Date beginning = new Date(0);
... gets me zero time on Jan 1, 1970. But what's an easy way to get zero time today and zero time tomorrow?
UPDATE; I did this, but surely there's an easier way?
Calendar calStart = new GregorianCalendar();
calStart.setTime(new Date());
calStart.set(Calendar.HOUR_OF_DAY, 0);
calStart.set(Calendar.MINUTE, 0);
calStart.set(Calendar.SECOND, 0);
calStart.set(Calendar.MILLISECOND, 0);
Date midnightYesterday = calStart.getTime();
Calendar calEnd = new GregorianCalendar();
calEnd.setTime(new Date());
calEnd.set(Calendar.DAY_OF_YEAR, calEnd.get(Calendar.DAY_OF_YEAR)+1);
calEnd.set(Calendar.HOUR_OF_DAY, 0);
calEnd.set(Calendar.MINUTE, 0);
calEnd.set(Calendar.SECOND, 0);
calEnd.set(Calendar.MILLISECOND, 0);
Date midnightTonight = calEnd.getTime();
Apache Commons Lang
http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html#isSameDay(java.util.Date, java.util.Date)
java.util.Calendar
JDK 8 - java.time.LocalTime and java.time.LocalDate
Joda-Time
If you're using a JDK < 8, I recommend Joda Time, because the API is really nice:
Since version 2.3 of Joda Time
DateMidnight
is deprecated, so use this:Pass a time zone if you don't want the JVM’s current default time zone.
Remember,
Date
is not used to represent dates (!). To represent date you need a calendar. This:will create a
Calendar
instance representing present date in your current time zone. Now what you need is to truncate every field below day (hour, minute, second and millisecond) by setting it to0
. You now have a midnight today.Now to get midnight next day, you need to add one day:
Note that adding
86400
seconds or 24 hours is incorrect due to summer time that might occur in the meantime.UPDATE: However my favourite way to deal with this problem is to use DateUtils class from Commons Lang:
It uses
Calendar
behind the scenes...these methods will help you-
and
As of JodaTime 2.3, the
toDateMidnight()
is deprecated.From Upgrade from 2.2 to 2.3
Here is a sample code without
toDateMidnight()
method.Code
Output (may be different depending on your local time zone)