1. 程式人生 > >【Java】日期&字串互轉

【Java】日期&字串互轉

DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
DateFormat format2 = new SimpleDateFormat("yyyy年MM月dd日 HH時mm分ss秒");
Date date = null;
String str = null;

// String轉Date
str = "2007-1-18";
try {
    date = format1.parse(str);
    System.out.println(date);
    date = format2.parse(str); // Exception
System.out.println(date); } catch (ParseException e) { e.printStackTrace(); } // Date轉String date = new Date(); str = format1.format(date); System.out.println(str); str = format2.format(date); System.out.println(str);

在字串解釋成時間型別時出現Exception:

// Exception in thread "main" java.text.ParseException: Unparseable date: "02001.July.04 AD 12:08 PM"  
// at java.text.DateFormat.parse(DateFormat.java:337) // at com.test.TestMain.main(TestMain.java:18) // 加上本地化就OK了 System.out.println(new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa",Locale.US).parse("02001.July.04 AD 12:08 PM")); System.out.println(Locale.getDefault());