我有一個DateTimehelper.class其中我已經執行了一些日期相關的操作和代碼工作正常,直到我從客戶得到的問題,他們得到的日期格式錯誤。以下是我的類:SimpleDateFormatter以錯誤的格式返回日期
public class DateTimeHelper {
private static Calendar cal;
public static DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static DateFormat shortDateFormatter = new SimpleDateFormat("yyyy-MM-dd");
public static DateFormat shortDateFormatterWithSlash = new SimpleDateFormat("dd/MM/yyyy");
public static DateFormat dateFormat_dd_MM_yyyy = new SimpleDateFormat("dd-MM-yyyy");
DateTimeHelper helper;
/**
* set UTC Date to the calendar instance
*
* @param strDate
* date to set
*/
public static void setDate(String strDate) {
try {
Date date = (Date) formatter.parse(strDate);
cal = Calendar.getInstance();
cal.setTime(date);
updateDateTime();
}
catch (ParseException e) {
e.printStackTrace();
}
}
/**
* update date every 1 second
*/
private static void updateDateTime() {
final Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
try {
cal.add(Calendar.SECOND, 1);
handler.postDelayed(this, 1000);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
/***
* get updated date from calendar in custom date format
*
* @return date
*/
public static String getDate() {
String strDate = null;
try {
strDate = formatter.format(cal.getTime());
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return strDate;
}
}
時候見我發現格式日期日誌:2014-0011-25 04:45:38
這是完全錯誤的我猜是因爲一個月應該是11而不是0011
但是,當我嘗試使用下面來驗證此日期函數;它表示日期是有效的。
public static boolean isValidDate(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
它怎麼可能是一個有效的日期? 爲什麼我以錯誤的格式取得日期?
這個問題是很隨意的,因爲它僅由用戶的報道,但我通過SimpleDateFormater和日曆 API
請幫助的行爲十分驚訝。
我認爲你的日曆創建問題 – 2014-11-25 08:00:30
我認爲這是一個競爭條件,因爲日曆和SimpleDateFormat的是不是線程安全的。你的變量是靜態的,你正在使用在另一個線程上運行的Runnable。 – 2014-11-25 08:04:37
但2014-0011-25怎麼能有效? – dd619 2014-11-25 09:00:03