2013-08-07 50 views
-4

這裏是代碼我使用:爲什麼我的日期解析返回一個奇怪的日期?

String string = "08/07/2013".replace('/', '-'); 
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(string); 

爲什麼至今的回報: 「文1月3日00:00:00 EST 14」?這完全不是我告訴它使用的日期格式。

編輯:我需要這種格式,因爲我使用的數據庫需要這種格式。

+5

因爲格式和字符串不匹配。 – NINCOMPOOP

+0

你的印刷說明是什麼? – bowmore

+0

@TheNewIdiot你是什麼意思?字符串等於「08-07-2013」​​ –

回答

4

用於解析日期字符串的格式與它不匹配。您正在使用yyyy作爲08

使用以下格式:

new SimpleDateFormat("dd-MM-yyyy") 

,爲什麼在所有人都在更換/-?你可以建立的模式只有原始的字符串:

String string = "08/07/2013" 
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(string); 

,如果你想在yyyy-MM-dd格式的日期字符串,那麼你可以格式化使用dateDateFormat#format(Date)方法:

String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(date); 

參見:

+0

我不能使用這種格式的格式,所以我可以將它傳遞給使用這種格式的數據庫。 –

+0

@ jacen.garriss。然後您可以使用所需的格式重新格式化日期。 –

+0

我以08/07/2013的格式向用戶顯示,但我想將其轉換爲數據庫中使用的其他格式。 –

0

好吧我sugestion是愚蠢的,但如果你需要這種格式試試這個

String[] arr = "08/07/2013".split("/"); 
String newString = arr[2]+"-"+arr[1]+"-"arr[0]; 
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(newString); 

注意如果您的原始〜應變是格式爲「MM/DD/YYYY使用此:

String newString = arr[2]+"-"+arr[0]+"-"arr[1]; 
1

當你使用字符串指定一些簡單的日期格式例如「yyyy-MM-dd」,你必須以相同的格式提供你的日期以獲得一個日期對象,例如。 「1991-07-24」。

String mydate = "1991/07/24"; 
Date formattedDate = new SimpleDateFormat("yyyy/MM/dd").parse(mydate); 

現在如果你想把它轉換成任何其他格式,你可以做到這一點通過格式化這個日期對象成perticular格式..

String dateInOtherFormat = new SimpleDateFormat("dd-MMM-yyyy").format(formatteddate); 

和dateInOtherFormat的輸出會.. 。24-JUL-1991。