The Calendar class
In the previous section, we explored the Date
class, where we learned about Date
methods and how to operate on them using simple date format standards. In this section, we will learn about the Calendar
class, which is similar to the Date
class, but with some extra features. Let's see what they are and how we can use them to extract our date formats using the Calendar
class.
First, we will create a class with a different name to avoid conflict. To create a Calendar
instance, run the following:
Calendar cal=Calendar.getInstance(); Date d=new Date();
The steps are similar to those for the Date
class. However, the Calendar
object has some unique features that date doesn't support. Let's explore them.
Use the following code snippet:
Calendar cal=Calendar.getInstance(); SimpleDateFormat sd=new SimpleDateFormat("M/d/yyyy hh:mm:ss"); System.out.println(sd.format(cal.getTime()));
The output for the preceding code will be:
Output displaying date and time using calendar...