--sunfruit
在處理日期的格式轉換的時候總結些經驗,和大家分享,如下:
String text ="1996-2-1";
Date d = null;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setLenient(false);//這個的功能是不把1996-13-3 轉換為1997-1-3
try
{
d = df.parse(text);
}
catch(Exception e)
{
d=new Date();
System.out.println("你輸入的日期不合法,請重新輸入");
}
String sdata=df.format(d);
System.out.println(sdata);
這樣輸入1996-2-31這樣的數據也會驗證出來錯誤的,但是前提是要設置Lenient為false