我试图获得两个日期之间的差异,但我坚持将字符串转换为日期。
我的代码是:
//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());
在某些时候,我正在尝试从数据库中检索日期:
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)