爲了更好地格式化日期,解析日期字符串,Java提供了SinpleDateFormat類。SimpleDateFormat是DateFormat子類,但比DateFormat更簡單,功能更強大。
SimpleDateFormat可以非常靈活地格式化Date,也可用於解析各種格式的日期字符串。創建SimpleDateFormat
對象時需要傳入一個pattern字符串,這個pattern不是正則表達式,而是一個日期模板字符串:
程序示例如下:
package date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* SimpleDateFormat使用簡介
* @author Hai.Pan
*
*/
public class TestSimpleDateFormat {
public static void main(String[] args) throws ParseException {
Date d = new Date();
System.out.println(d);//Wed Apr 09 23:36:13 CST 2014
//創建一個SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
String dateStr = sdf.format(d);
System.out.println(dateStr);//2014年04月09日
String str ="2014年04月08日";
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
System.out.println(sdf2.parse(str));//Tue Apr 08 00:00:00 CST 2014
}
}