Java Reference
In-Depth Information
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
// Parse the text into a Date object
Date dt = sdf.parse(input, new ParsePosition(0));
System.out.println(dt);
// Get the Calendar instance
Calendar cal = Calendar.getInstance();
// Set the time
cal.setTime(dt);
// Print time parts
System.out.println("Hour:" + cal.get(Calendar.HOUR));
System.out.println("Minute:" + cal.get(Calendar.MINUTE));
System.out.println("Second:" + cal.get(Calendar.SECOND));
System.out.println("Millisecond:" +
cal.get(Calendar.MILLISECOND));
}
}
Thu Apr 03 09:10:40 CST 2003
Hour:9
Minute:10
Second:40
Millisecond:325
Formatting Numbers
In this section, I will discuss how to format numbers. I will also discuss how to parse a string to create a Number object.
The following two classes can be used to format and parse numbers:
java.text.NumberFormat
java.text.DecimalFormat
The NumberFormat class is used to format a number in a particular locale's predefined format. The DecimalFormat
class is used to format a number in a format of your choice in a particular locale. You can use a getXXXInstance()
method of the NumberFormat class to get the instance of a formatter object, where Xxx can be replaced by Number ,
Currency , Integer , or Percent, or just getInstance() . These methods are overloaded. If you call them without any
argument, they return a formatter object for the default locale. Call the format() method, passing the number as an
argument to get the formatted number as a string.
NumberFormat formatter;
// Get number formatter for default locale
formatter = NumberFormatter.getNumberInstance();
 
Search WWH ::




Custom Search