How to Convert a Date to Calendar in Java
Despite being named "Date," the java.util.Date class does not represent what we typically think of as a date. Rather, it is an instant in time measured in milliseconds since midnight GMT, January 1, 1970 (known as the "Unix epoch."). This "date" does not reflect calendars used in other countries, such as the traditional Japanese calendar or the Hebrew calendar.
To address this, Java provides the java.util.Calendar class. You can still use the Date class for simple comparisons, such as determining which of two dates is earlier. On the other hand, if you need to manipulate individual units or express a date using an international calendar, then you should use a Calendar object. Java provides methods that convert between Dates and Calendars so that you can use both types interchangeably.
Instructions
-
-
1
Retrieve the java.util.Date object that you wish to convert. If the value you have is merely a number of milliseconds since the Unix epoch (such as that returned by a call to System.currentTimeMillis), you can get an equivalent Date object by passing the value to a call to "new Date."
-
2
Create a new Calendar object by calling "new Calendar()" with no arguments, which will initialize it with the default time zone and locale for the system on which the application is currently running. Alternatively, you can pass an explicit time zone and locale to this constructor if you wish to convert the date to a time zone other than the default.
-
-
3
Call the "setTime" method on the Calendar object, passing it the Date object that you wish to convert. The Calendar will now represent the same time as the Date object.
-
4
Call the "get" and "set" method on the Calendar object to manipulate its individual components, such as the month, day, year, number of hours, number of minutes and others.
-
5
If you need to retrieve a Date object that corresponds to this Calendar after performing some manipulations, call the "getTime" method, which returns a Date.
-
1
References
- Photo Credit calendar image by Christopher Hall from Fotolia.com