A Calendar maps out time. With it, we divide time into days, into months and years. In Java, a Calendar is used to manage time values.
DateFormat
Other classes too are helpful. A Date instance is used to store a point in time. A DateFormat
helps us convert time Strings.
This example combines several time-oriented classes in Java. It uses the DateFormat
class
to parse a String
into a Date. And it sets up a Calendar from that Date.
DateFormat
class
provides the parse method. With parse, we can convert a String
into its Date representation.DateFormat
parse method returns a Date instance.import java.text.DateFormat; import java.text.ParseException; import java.util.Calendar; import java.util.Date; public class Program { public static void main(String[] args) throws ParseException { // Get DateFormat and parse a String into a Date. DateFormat format = DateFormat.getInstance(); Date date = format.parse("05/14/14 1:06 PM"); // Set date in a Calendar. Calendar cal = Calendar.getInstance(); cal.setTime(date); // Get hours from the Calendar. int hours = cal.get(Calendar.HOUR_OF_DAY); if (hours == 13) { System.out.println(true); } } }true
Two Calendars can be compared. After initializing them with set()
, we call after and before to see which is earlier in time.
int
indicates the relative order of the two Calendars.import java.util.Calendar; public class Program { public static void main(String[] args) { // Set date to 5/13. Calendar cal = Calendar.getInstance(); cal.set(2014, 5, 13); // Set date to 5/14. Calendar cal2 = Calendar.getInstance(); cal2.set(2014, 5, 14); // See if first date is after, before second date. boolean isAfter = cal.after(cal2); boolean isBefore = cal.before(cal2); System.out.println(isAfter); System.out.println(isBefore); // Compare first to second date. int compare = cal.compareTo(cal2); System.out.println(compare); } }false true -1
GetInstance
The DateFormat
and Calendar classes are abstract
ones. We cannot instantiate them with new. But with getInstance
we can use their helpful methods.
We access values from a Calendar with the get method. To get a certain field, we pass a constant int
like Calendar.HOUR_OF_DAY
. This returns that value.
We can display Calendars with format strings and the String.format
method. After a lowercase "t" we specify our time-formatting characters.
Writing custom methods to deal with dates is a burden. Built-in code, as we find in the Date, Calendar and DateFormat
classes, is already tested and correct.