What is DateUtils.toCalendar() in Java?
Overview
toCalendar() is a DateUtils which is used to convert the given Date object to an object of the Calendar class. The method optionally takes the timezone parameter.
How to import DateUtils
The definition of DateUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
You can import the DateUtils class as follows:
import org.apache.commons.lang3.time.DateUtils;
Syntax
public static Calendar toCalendar(final Date date)
Parameters
final Date date: The object of theDateclass to convert toCalendarclass.
Return value
This method returns an instance of the Calendar class with the same date.
Code
In the code below, we convert the current date to the Calendar class instance and print the converted object to the console.
import org.apache.commons.lang3.time.DateUtils;import java.util.Calendar;import java.util.Date;public class Main{public static void main(String[] args) {// Define date objectDate currDate = new Date();// Convert to object of Calendar classCalendar calendar = DateUtils.toCalendar(currDate);// Print the objectsSystem.out.printf("%s converted to Calendar Class - %s", currDate, calendar);}}
Output
The output of the code will be as follows:
Sun Nov 21 03:46:46 IST 2021 converted to Calendar Class -
java.util.GregorianCalendar[time=1637446606989,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Kolkata",offset=19800000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2021,MONTH=10,WEEK_OF_YEAR=46,WEEK_OF_MONTH=3,DAY_OF_MONTH=21,DAY_OF_YEAR=325,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=3,HOUR_OF_DAY=3,MINUTE=46,SECOND=46,MILLISECOND=989,ZONE_OFFSET=19800000,DST_OFFSET=0]