Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate a Date for a 00:00:00 a.m. of a today?

Tags:

java

calendar

I need to calculate a java.util.Date for a beginning of a today day (00:00:00 a.m. of a today day). Does someone know something better than resetting fields of java.util.Calendar:

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);
like image 650
Nulldevice Avatar asked Jun 22 '10 10:06

Nulldevice


3 Answers

If you don't bother about time zones then your solution is ok. Otherwise it's worth to look at JodaTime.

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

like image 94
Roman Avatar answered Oct 13 '22 01:10

Roman


The following code will return the current date's calendar object with time as 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 consider the timezone values and is almost same as your code. Only difference is that it is done all resets to 0 in single line.

like image 26
Joe Avatar answered Oct 13 '22 00:10

Joe


This solution can be better as it does not make use of java's 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));
    }
}
like image 45
moni Avatar answered Oct 13 '22 02:10

moni