2012-09-01 67 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