How to calculate date for 00:00:00 AM today?

I need to calculate java.util.Date for the start of today (00:00:00 today morning). Someone knows something better than dropping java.util.Calendar fields:

Calendar cal = Calendar.getInstance(); cal.set(Calendar.AM_PM, Calendar.AM); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); 
+6
java calendar
source share
7 answers

If you're not worried about time zones, your decision is fine. Otherwise, it's worth a look at JodaTime.

If you ultimately decide to switch to JodaTime, you can use the DateMidnight class, which is supposed to be used in your situation.

+7
source share

The following code will return the current time calendar object with a time like 00:00:00

 Calendar current = Calendar.getInstance(); current.set(current.get(Calendar.YEAR),current.get(Calendar.MONTH),current.get(Calendar.DATE),0,0,0); 

It will not take into account time zone values ​​and is almost the same as your code. The only difference is that it is performed by dropping to 0 in one line.

+4
source share

This solution might be better since it does not use java heavy element Calender

 public class DateTest { public static void main(String[] args) { SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); long time = dateFormat.parse(dateFormat.format(new Date())).getTime(); System.out.println("todays start date : " + new Date(time)); } } 
+2
source share

I am in the same boat, and what you have provided is how I do it. I have a DateUtil.stripToMidnight(...) function ...

But just remember to consider TimeZones when doing all this, since here 0:00 here will not be the same in another part of the world.

There may be a way to do this in JodaTime, but I don't know about that.

+1
source share

With date4j library:

 DateTime start = dt.getStartOfDay(); 
+1
source share

Another option without additional libraries:

 import java.sql.Date; public class DateTest { public static void main(String[] args) { long MS_PER_DAY = 24L * 60 * 60 * 1000; long msWithoutTime = (System.currentTimeMillis() / MS_PER_DAY) * MS_PER_DAY; Date date = new Date( msWithoutTime ); System.out.println( date.toGMTString()); } } 
0
source share

As in java8, this can be done as follows, assuming you don't need a time zone.

 LocalDateTime localDateTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT); Date midnight = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); 
0
source share

All Articles