This content originally appeared on DEV Community and was authored by Paul Ngugi
GregorianCalendar is a concrete subclass of the abstract class Calendar. An instance of java.util.Date represents a specific instant in time with millisecond precision. java.util.Calendar is an abstract base class for extracting detailed calendar information, such as the year, month, date, hour, minute, and second. Subclasses of Calendar can implement specific calendar systems, such as the Gregorian calendar, the lunar calendar, and the Jewish calendar. Currently, java.util.GregorianCalendar for the Gregorian calendar is supported in Java, as shown in Figure below. The add method is abstract in the Calendar class, because its implementation is dependent on a concrete calendar system.
You can use new GregorianCalendar() to construct a default GregorianCalendar with the current time and new GregorianCalendar(year, month, date) to construct a GregorianCalendar with the specified year, month, and date. The month parameter is 0 based—that is, 0 is for January.
The get(int field) method defined in the Calendar class is useful for extracting the date and time information from a Calendar object. The fields are defined as constants, as shown in Table below.
The program gives an example that displays the date and time information for the current time.
Current time is Mon Jun 17 19:42:58 EAT 2024
YEAR: 2024
MONTH: 5
DATE: 17
HOUR: 7
HOUR_OF_DAY: 19
MINUTE: 42
SECOND: 58
DAY_OF_WEEK: 2
DAY_OF_MONTH 17
DAY_OF_YEAR 169
WEEK_OF_MONTH 4
WEEK_OF_YEAR 25
AM_PM 1
September 11, 2001 is a Tuesday
The set(int field, value) method defined in the Calendar class can be used to set a field. For example, you can use calendar.set(Calendar.DAY_OF_MONTH, 1) to set the calendar to the first day of the month.
The add(field, value) method adds the specified amount to a given field. For example, add(Calendar.DAY_OF_MONTH, 5) adds five days to the current time of the calendar. add(Calendar.DAY_OF_MONTH, -5) subtracts five days from the current time of the calendar.
To obtain the number of days in a month, use calendar.getActualMaximum(Calendar.DAY_OF_MONTH). For example, if the calendar were for March, this method would return 31.
You can set a time represented in a Date object for the calendar by invoking calendar.setTime(date) and retrieve the time by invoking calendar.getTime().
This content originally appeared on DEV Community and was authored by Paul Ngugi
Paul Ngugi | Sciencx (2024-06-17T16:48:16+00:00) Case Study: Calendar and GregorianCalendar. Retrieved from https://www.scien.cx/2024/06/17/case-study-calendar-and-gregoriancalendar/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.