2012-01-02 47 views
2

我有時間爲「2011-12-03 12時00分19秒」如何將它轉換成「週五2011年12月2」,我知道這http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html,但給我的錯誤:Android/java時間格式?

Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date 
    at java.text.DateFormat.format(Unknown Source) 
    at java.text.Format.format(Unknown Source) 
    at com.timestamp.NewTimeStamp.<init>(NewTimeStamp.java:21) 
    at com.timestamp.NewTimeStamp.main(NewTimeStamp.java:35) 

我的代碼是::

String mytime ="2011-12-03 12:00:19"; 
String pattern = "EEE d MMMMM yyyy"; 
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); 

     Date date = new Date(mytime); 
     String time = dateFormat.format(date); 

     System.out.println("=== > " + time); 
+1

什麼是你'pattern'了? – Vaandu 2012-01-02 10:13:18

+0

String pattern =「EEE d MMMMM yyyy」; – 2012-01-02 10:15:29

+2

日期日期=新日期(mytime);我認爲這條線給你錯誤。在該行之前和之後加上調試代碼System.out.println(「1」)&(「2」),然後執行並查看該行是否真的產生錯誤或什麼? – Android 2012-01-02 10:17:45

回答

7

將您的輸入轉換爲Date然後格式化。

 String mytime ="2011-12-03 12:00:19"; 
     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss"); 
     Date myDate = dateFormat.parse(mytime); 
     System.out.println("=== > " + myDate); 
     SimpleDateFormat timeFormat = new SimpleDateFormat("EEE d MMMMM yyyy"); 
     String time = timeFormat.format(myDate); 
     System.out.println("=== > " + time); 

輸出:

D:\Work\Stand alone Java classes>javac Test2.java && java Test2 
=== > Wed Jan 12 12:00:19 IST 2011 
=== > Wed 12 January 2011 
+0

thnx這麼多,我忘了把它轉換成日期第一... – 2012-01-02 10:27:24

+0

但是,當月份它的迴歸一月實際上是十二月? – 2012-01-02 10:31:31

+0

SimpleDateFormat dateFormat = new SimpleDateFormat(「yyyy-dd-MM HH:mm:ss」);是對的 – 2012-01-02 10:34:22