2012-10-02 35 views
0

我搜索了這個問題,但發現只是從字符串更改爲日期,然後將日期顯示爲字符串。 我有一個要求,我在哪裏接收日期字符串格式,然後我必須分析,在日期對象,並輸入Database.But每當我將字符串轉換爲日期它給了我錯誤的輸出。請建議。提前致謝。Java字符串日期轉換問題

String subscribedDate="2012-09-28 11:00:00"; 
String oldFormat = "yyyy-mm-dd hh:mm:ss"; 
SimpleDateFormat sdf1 = new SimpleDateFormat(oldFormat); 
Date dates=sdf1.parse(subscribedDate); 
System.out.println(dates); 
//code for entering dates in database. 

輸出: 週六1月28日零時09分00秒格林尼治標準時間2012(這是不正確!)。我想作爲2012-09-28 11:00:00

回答

1

我想在第二行中的oldFormat變量應該是

oldFormat = "yyyy-MM-dd HH:mm:ss"; // hours counted 0~23 

oldFormat = "yyyy-MM-dd hh:mm:ss"; // hours counted 0~11 
1

嘗試oldFormat改變

String oldFormat = "yyyy-MM-dd hh:mm:ss"; 

其中MM是大寫字母。

0

試試這個:

 String oldFormat = "yyyy-MM-dd hh:mm:ss"; 

docs找出原因。

6

您的格式字符串錯誤。 yyyy-mm-dd hh:mm:ss基本上是說「年 - 小 - 天小時:分鐘:秒」,我敢肯定你不想要。

你想

String oldFormat = "yyyy-MM-dd hh:mm:ss"; 

看一看在SimpleDateFormat文檔的更多信息

+2

1我也使用'HH' 24小時的時間。 –

+1

@peter +1,好點 – MadProgrammer

+0

@MadProgrammer非常感謝! 「MM」是完美的解決方案! –

3

首先月份字段使用MM而不是mm這是分鐘表示。

其次,格式化程序可以用來打印所需格式的日期。

String subscribedDate="2012-09-28 11:00:00"; 
String oldFormat = "yyyy-MM-dd hh:mm:ss"; 
SimpleDateFormat sdf1 = new SimpleDateFormat(oldFormat); 
Date dates=sdf1.parse(subscribedDate); 
System.out.println(sdf1.format(dates)); 
// code for entering dates in database. 
+0

+1爲額外的格式聲明 – MadProgrammer