Java Convert Date to Calendar Without Time
Tags: Java Date Java Calendar TimeUtil
In this Java core tutorial, we learn how to convert a Date object into a Calendar object without zero values for hour, minute, seconds, and milliseconds.
How to convert Date to Calendar without Time in Java
At this first step, we create a new Java class named TimeUtil, and implement a new method named convertDateToCalendarWithoutTime(Date date), in this method we follow these step to convert Date to Calendar.
- Create a new Calendar object.
- Use the Calendar.setTime(Date date) to set Date value to the above Calendar object.
- Use the Calendar.set(int field, int value) method to set value of time to zero.
TimeUtil.java
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class TimeUtil {
/**
* Convert a Date object to Calendar object without time
* @param date the Date object
* @return the Calendar object without time
*/
public static Calendar convertDateToCalendarWithoutTime(Date date) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
return calendar;
}
}
In the following example Java program, we learn how to use the TimeUtil class above to convert a Date object to Calendar without time object.
ConvertDateToCalendarWithoutTimeExample.java
import java.util.Calendar;
import java.util.Date;
public class ConvertDateToCalendarWithoutTimeExample {
public static void main(String... args) {
Date date = new Date();
// Convert Date to Calendar Without Time
Calendar calendar = TimeUtil.convertDateToCalendarWithoutTime(date);
System.out.println("Date: " + date);
System.out.println("Calendar: " + calendar);
}
}
Date: Sun Aug 14 17:42:03 ICT 2022
Calendar: java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Bangkok",offset=25200000,dstSavings=0,useDaylight=false,transitions=3,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=7,WEEK_OF_YEAR=34,WEEK_OF_MONTH=3,DAY_OF_MONTH=14,DAY_OF_YEAR=226,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=5,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=25200000,DST_OFFSET=0]
Happy Coding 😊