三、将文本数据解析成日期对象r
  如果我们有一个文本字符串包括了一个格式化了的日期对象, 而我们希望解析这个字符串并从文本日期数据创建一个日期对象. 我们将再次以格式化字符串"MM-dd-yyyy" 调用SimpleDateFormat类, 可是这一次, 我们使用格式化解析而不是生成一个文本日期数据. 我们的样例, 显示在以下, 将解析文本字符串"9-29-2001"并创建一个值为001736000000 的日期对象.
  样例程序:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateExample3 {
public static void main(String[] args) {
// Create a date formatter that can parse dates of
// the form MM-dd-yyyy.
SimpleDateFormat bartDateFormat =
new SimpleDateFormat("MM-dd-yyyy");
// Create a string containing a text date to be parsed.
String dateStringToParse = "9-29-2001";
try {
// Parse the text version of the date.
// We have to perform the parse method in a
// try-catch construct in case dateStringToParse
// does not contain a date in the format we are expecting.
Date date = bartDateFormat.parse(dateStringToParse);
// Now send the parsed date as a long value
// to the system output.
System.out.println(date.getTime());
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
  四、使用标准的日期格式化过程
  既然我们已经能够生成和解析定制的日期格式了, 让我们来看一看怎样使用内建的格式化过程. 方法 DateFormat.getDateTimeInstance() 让我们得以用几种不同的方法获得标准的日期格式化过程. 在以下的样例中, 我们获取了四个内建的日期格式化过程. 它们包含一个短的, 中等的, 长的, 和完整的日期格式.
import java.text.DateFormat;
import java.util.Date;
public class DateExample4 {
public static void main(String[] args) {
Date date = new Date();
DateFormat shortDateFormat =
DateFormat.getDateTimeInstance(
DateFormat.SHORT,
DateFormat.SHORT);
DateFormat mediumDateFormat =
DateFormat.getDateTimeInstance(
DateFormat.MEDIUM,
DateFormat.MEDIUM);
DateFormat longDateFormat =
DateFormat.getDateTimeInstance(
DateFormat.LONG,
DateFormat.LONG);
DateFormat fullDateFormat =
DateFormat.getDateTimeInstance(
DateFormat.FULL,
DateFormat.FULL);
System.out.println(shortDateFormat.format(date));
System.out.println(mediumDateFormat.format(date));
System.out.println(longDateFormat.format(date));
System.out.println(fullDateFormat.format(date));
}
}
  注意我们在对 getDateTimeInstance的每次调用中都传递了两个值. 第一个?数是日期风格, 而第二个?数是时间风格. 它们都是基本数据类型int(整型). 考虑到可读性, 我们使用了DateFormat 类提供的常量: SHORT, MEDIUM, LONG, 和FULL. 要知道获取时间和日期格式化过程的很多其它的方法和选项, 请看Sun 公司Web网站上的解释.
  执行我们的样例程序的时候, 它将向标准输出设备输出以下的内容:
  9/29/01 8:44 PM
  Sep 29, 2001 8:44:45 PM
  September 29, 2001 8:44:45 PM EDT
  Saturday, September 29, 2001 8:44:45 PM EDT