Archive for August 3rd, 2009

Format Date/Time Using System package

August 3, 2009
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
Advertisements

Formating String using String Class

August 3, 2009
public class FormatString
{
public static void main(String [] arg)
{
Object ob[] = {“prabir”,27};
st = String.format(“My name is %s, I am %d years old”, ob);
System.out.println(st);
st = String.format(“The value of PI is:%f”, Math.PI);
System.out.println(st);
//specify no. of decemals
st = String.format(“The value of PI is:%.2f”, Math.PI);
System.out.println(st);
}
}
Here
  • s expecting string value.
  • d expecting numeric value without decimal.
  • f expecting float value.
  • .2 specify no of decimal places.
Output:
The value of PI is: 3.141593
The value of PI is: 3.14