2011-12-17 48 views
1

我在我的應用程序中某處存儲了一個日期字符串。像這樣:安卓日期本地化

Date updatedDate = new Date(); 

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(_context); 
SharedPreferences.Editor editor = settings.edit(); 
editor.putString(Constants.Preferences.LastUpdateDateKey, updatedDate.toLocaleString()); 
editor.commit(); 

當語言是英語時,一切正常。

但是,當我將它切換到法語。

此代碼拋出IllegalArgumentException

String lastUpdateDateString = settings.getString(Constants.Preferences.LastUpdateDateKey, null); 

if(lastUpdateDateString!=null){    
      lastUpdateDate = new Date(Date.parse(lastUpdateDateString));    
     } 

它拋出在Date.parse

英語和法語中,updatedDate.toLocaleString()是以下格式:2011-12-16 22:13 :32

它必須與語言切換有關。有沒有辦法說使用格式解析日期?

回答

1

您可以使用SimpleDateFormat這會給你的日期,這將是固定的各個地區

語法是SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

的,如果你想要得到的字符串,那麼你可以使用

dateFormat.format(new Date()) 

,如果你想從字符串得到日期然後

Date date = dateFormat.parse(strDate) 
1

我通過使用SimpleFormatter找到了答案。