Monday, August 3, 2009

Format Date/Time Using System package

You can easily format date/Time using System package in java.

public class PrintDateTime
{
public static void main(String [] arg)
{
//printf is not line feed and carriage return, so you have to put a line break.
System.out.printf("Today is: %1$tm/%1$te/%1$tY", Calendar.getInstance());
System.out.print("\n");
System.out.printf("Time is: %tr", Calendar.getInstance());
System.out.print("\n");
System.out.printf("Time is: %tT", Calendar.getInstance());
}
}

Here
  • t means, you want to deal with date/time.
  • m means, you want month from the date.
  • e means, you want day from the date.
  • Y means, you want Year from the date.
  • r means, you want time as 12-hour clock with AM/PM
  • T means, you want time as 24-hour clock.
Output:
Today is: 08/3/2009
Time is: 09:55:45 PM
Time is: 21:55:45

No comments:

Post a Comment