2013-05-13 29 views
-3

我有一個字符串2012-10-23,我需要轉換成一個Date對象。解析一個字符串到日期

我可以直接通過這個字符串下面的函數

Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(string); 
+2

'yyyy-MM-dd'將是正確的 – 2013-05-13 11:11:14

+4

你問之前讀過SimpleDateFormat的javadoc嗎?如果是這樣,你爲什麼不按照那裏的明確解釋? – creinig 2013-05-13 11:13:39

回答

4
Date date = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(string); 

2012-10-23您的格式應爲"yyyy-MM-dd"

+0

爲什麼我的答案已關閉 – PSR 2013-05-13 11:16:54

+0

@PSR:你應該給你的答案添加一點解釋。也許它會被取消刪除。 – 2013-05-13 11:19:11

+1

@PSR,因爲當你編輯出錯誤的時候,有新的答案,你的答案是重複的。我放棄了我的反刪除投票,但它需要3次取消投票。你的原始答案看起來像[在西方問題中最快槍](http://meta.stackexchange.com/questions/9731/fastest-gun-in-west-problem) – Habib 2013-05-13 11:19:27

2
String string = "2012-10-23"; 
Date date = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(string); 


Letter Date or Time Component Presentation Examples 
G Era designator Text AD 
y Year Year 1996; 96 
Y Week year Year 2009; 09 
M Month in year Month July; Jul; 07 
w Week in year Number 27 
W Week in month Number 2 
D Day in year Number 189 
d Day in month Number 10 
F Day of week in month Number 2 
E Day name in week Text Tuesday; Tue 
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1 
a Am/pm marker Text PM 
H Hour in day (0-23) Number 0 
k Hour in day (1-24) Number 24 
K Hour in am/pm (0-11) Number 0 
h Hour in am/pm (1-12) Number 12 
m Minute in hour Number 30 
s Second in minute Number 55 
S Millisecond Number 978 
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00 
Z Time zone RFC 822 time zone -0800 
X Time zone ISO 8601 time zone -08; -0800; -08:00 
+0

爲什麼downvote.Please解釋 – PSR 2013-05-13 11:11:19

+0

對不起,我做了 – PSR 2013-05-13 11:11:46

+0

因爲格式不對, – Habib 2013-05-13 11:11:56

0

,你不行,這是怎麼

String string = "2012-10-23"; 
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(string);