The following code snippet shows you how to remove time information from the java.util.Date
object. The static method removeTime()
in the code snippet below will take a Date
object as parameter and will return a new Date
object where the hour, minute, second and millisecond information hasbeen reset to zero. To do this, we use the java.util.Calendar
. To remove time information, we set the calendar fields of Calendar.HOUR_OF_DAY
, Calendar.MINUTE
, Calendar.SECOND
and Calendar.MILLISECOND
to zero.
package org.kodejava.util;
import java.util.Calendar;
import java.util.Date;
public class DateRemoveTime {
public static void main(String[] args) {
System.out.println("Now = " + removeTime(new Date()));
}
private static Date removeTime(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
}
The result of the code snippet above is:
Now = Sat Nov 20 00:00:00 CST 2021
In the above code:
- An instance of
Calendar
is created usingCalendar.getInstance()
. - We set the
Calendar
time usingsetTime()
method and pass thedate
object. - The time fields (
HOUR_OF_DAY
,MINUTE
,SECOND
,MILLISECOND
) are set to zero.Calendar.HOUR_OF_DAY
is used for 24-hour clock. - The resulting
Calendar
instances time value is printed which should now represent the start of the day.
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Thanks Wayan for sharing this article. I have implemented this code in one of my project.