我試圖獲得兩個日期之間的差異,但我堅持將字符串轉換爲日期。與不同時區的兩個日期之間的差異
我的代碼是:
//create a date send it to the database as string
Date currentDate = new Date(); // date looks like: Sat Sep 01 10:20:14 EEST 2012
SaveToDB(currentDate.ToString());
在某些時候我; M試圖從數據庫中檢索日期:
String dateStringFromDb = GetDateFromDB(); //Sat Sep 01 10:20:14 EEST 2012
Date currentDate = new Date();
//now i'm trying to covnert the dateStringFromDb into a Date, this throws an exception
Date dbDate = DateFormat.getInstance().parse(dateStringFromDb); //this throws exception
long difference = currentDate.getTime() - dbDate.getTime(); // does this give me the correct difference in GMT even if timezones for the two dates are different?
能否請你點我正確的解決方案?
不幸的是,來自數據庫的日期是作爲字符串檢索的,我無法將其更改爲另一種類型。所以我需要將該字符串轉換爲Date()。
編輯:
的例外是:
java.text.ParseException: Format.parseObject(String) failed
at java.text.Format.parseObject(Unknown Source)
at main.Program.main(Program.java:20)
什麼是例外? – SiB
@SiB更新了異常問題 –