Menu
Topics Index
...
`

Time and Date Formatter - Java Example Program


Time and Date Formatter
import java.util.*;

class FormatTimeDate
{
    public static void main(String arg[])
    {
        Calendar cal = Calendar.getInstance();
        Formatter fmt = new Formatter();
        fmt.format("%tc", cal);
        System.out.println(fmt);
        fmt = new Formatter();
        fmt.format("%tT", cal);
        System.out.println(fmt);
        fmt = new Formatter();
        fmt.format("%tF %tB %tA", cal, cal, cal);
        System.out.println(fmt);
             
    }
}
OUTPUT

Mon Jan 13 01:27:38 PST 2014
01:27:38
2014-01-13 January Monday

DESCRIPTION

Note that the output of this program changes according to the date and time of the compilation. This is because we have used Calendar.getInstance() which returns the current date and time.

The first output line displays the standard date and time string formatted as day month date hh::mm::ss tzone year since we used %tc. The second output line is the display of hh:mm:ss (24-hour format) since we used %tT. The third output line is the display of year-month-day, full month name, full week-day name since we used %tF, %tB, %tA.

THINGS TO TRY
  • Try for all the suffixes mentioned in the table.
  • Instead ofCalendar, try to use Date, Long, or long as arguments for %t. Date can be created using new Date()

© meritcampus 2019

All Rights Reserved.

Open In App