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);
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.
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.
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With