[JAVA] 日期和字串轉換

  • 14168
  • 0

摘要:[JAVA] 日期和字串轉換

 

Date -> String

Date date = new Date();
String pattern1 = "yyyy/MM/dd HH:mm:ss";
String pattern2 = "yyyy-MM-dd-HH-mm-ss";
String pattern3 = "Z";

SimpleDateFormat sdf1 = new SimpleDateFormat(pattern1);
SimpleDateFormat sdf2 = new SimpleDateFormat(pattern2);
SimpleDateFormat sdf3 = new SimpleDateFormat(pattern3);

System.out.println(date.toString());
System.out.println(String.format("%s: %s", pattern1, sdf1.format(date)));
System.out.println(String.format("%s: %s", pattern2, sdf2.format(date)));
System.out.println(String.format("%s: %s", pattern3, sdf3.format(date)));


輸出結果
Wed Jul 10 17:11:51 CST 2013
yyyy/MM/dd HH:mm:ss: 2013/07/10 17:11:51
yyyy-MM-dd-HH-mm-ss: 2013-07-10-17-11-51
Z: +0800

 

String -> Date

String dateStr = "2013/07/10 18:15:20";
String pattern = "yyyy/MM/dd HH:mm:ss";

try 
{
    Date parseDate = new SimpleDateFormat(pattern).parse(dateStr);
 } 
catch (ParseException e) 
{
    //To something
}

 

 

http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

http://cooking-java.blogspot.tw/2010/03/java-string-to-date.html