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);
        fmt = new Formatter();
        fmt.format("%tT", cal);
        fmt = new Formatter();
        fmt.format("%tF %tB %tA", cal, cal, cal);

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


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.

  • 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