Menu
Topics Index
...
`

DateAndTime - Java Example Program


DateAndTime
import java.util.Calendar;

class ExampleOfDateAndTime
{
    public static void main(String arg[])
    {
        String months[] = {"JAN", "FEB", "MAR", "APR", "MAY", "JUNE", "JULY", "AUG", "SEPT", "OCT", "NOV", "DEC"};
        
        /*Create a calendar initialized with the
        current date and time in the default
        locale and timezone.*/
        Calendar cal = Calendar.getInstance();
        
        //Display current time and date information.
        System.out.println("Date :");
        System.out.print(months[cal.get(java.util.Calendar.MONTH)]);
        System.out.print(" " + cal.get(Calendar.DATE) + " ");// LINE D
        System.out.println(cal.get(Calendar.YEAR));
        
        System.out.println("Current Time: "); // LINE A
        System.out.print(cal.get(Calendar.HOUR) + ":");
        System.out.print(cal.get(Calendar.MINUTE) + ":");
        System.out.println(cal.get(Calendar.SECOND));
        
        //Set the time and date information and display it.
        cal.set(Calendar.HOUR, 10); // LINE C
        cal.set(Calendar.MINUTE, 29); // LINE C
        cal.set(Calendar.SECOND, 22); // LINE C
        
        System.out.println("Updated time"); // LINE B
        System.out.print(cal.get(Calendar.HOUR) + ":");
        System.out.print(cal.get(Calendar.MINUTE) + ":");
        System.out.println(cal.get(Calendar.SECOND));
    
    }
}
OUTPUT

Date :
APR 9 2014
Current Time:
7:40:20
Updated time
10:29:22

DESCRIPTION

In the above program we have created a String array months and stored all the months and we created a Calendar reference cal and invoked all the respective methods at LINE A to print the current date and time later we updated the time to 10:29:22 at LINE B and printed it.

THINGS TO TRY
  • Set the time at LINE C to 06:06:06 as shown below and print it.
    cal.set(Calendar.HOUR, 06);
         cal.set(Calendar.MINUTE, 06);
        cal.set(Calendar.SECOND, 06);
  • At LINE D
    System.out.println(" "+ cal.get(Calendar.DATE)+ " ");
    If we miss the space in between the double quotes it shows an error called empty character literal (or) unclosed character literal. check out this.

© meritcampus 2019

All Rights Reserved.

Open In App