This Java code demonstrates the use of the `Calendar` class...
August 27, 2025 at 06:15 PM
This Java code demonstrates the use of the Calendar
class and formatted output with the System.out.printf
method. Here's what the code does step by step:
-
Create a Calendar instance:
Calendar cal = Calendar.getInstance();
Calendar.getInstance()
creates a calendar object set to the current date and time based on the system's default locale and time zone.
-
Print the current date and time:
System.out.printf("The current date and time is: %tc\n\n", cal);
- The
%tc
format specifier formats theCalendar
instance (cal
) or aDate
object into a string that represents the complete date and time in the default format.
- The
-
Set a specific date and time in the calendar:
cal.set(1956, 9, 8, 5, 30, 12);
- Set the calendar to a specific date and time: October (Java months are zero-indexed, so
9
represents October), 8th, 1956, at 05:30:12.
- Set the calendar to a specific date and time: October (Java months are zero-indexed, so
-
Create a string containing a name:
String name = "Hitesh R. Pulimi";
-
Print another formatted output:
System.out.printf( "My name is %s.\nI was born at %Tr on a %tA,\nthe %teth ", name, cal, cal, cal );
My name is %s.
:%s
inserts thename
string.I was born at %Tr
:%Tr
formats the time (hour, minute, second) of theCalendar
instance.on a %tA
:%tA
outputs the full name of the day of the week (e.g., "Monday").the %teth
:%te
outputs the day of the month, and appending "th" is a formatting choice for ordinal numbers.- The
+
operator concatenates the two parts of the string.
Example Output:
If the system's current date is October 1, 2023, and the above code runs, the output will look something like this:
The current date and time is: Sun Oct 1 00:00:00 IST 2023
My name is Hitesh R. Pulimi.
I was born at 05:30:12 on a Monday,
the 8th
Key Points:
- The current date and time is fetched by
Calendar.getInstance()
. - The specific date and time (October 8, 1956) is set using
cal.set
. - Formatting specifiers (
%tc
,%s
,%Tr
,%tA
,%te
) are used withprintf
for nicely formatted output.
Generate your own explanations
Download our vscode extension
Read other generated explanations
Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node