2012-09-01 66 views
0

我試圖獲得兩個日期之間的差異,但我堅持將字符串轉換爲日期。與不同時區的兩個日期之間的差異

我的代碼是:

//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) 
+0

什麼是例外? – SiB

+0

@SiB更新了異常問題 –

回答

2

找到我會建議使用Joda Time API Java中的數據和時間相關操作。使用此API處理timezone和所有相關的轉換細微差別非常簡單。

0

您應該指定一個日期格式來匹配接收

如字符串格式。

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy"); 
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd"); 
String reformattedStr = myFormat.format(fromUser.parse(inputString)); 

一旦你有要求的格式兩個日期,然後應用最新的算術運算

爲DateString

的格式化標識符可以 http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html