I’m trying to obtain the difference between two dates but i’m stuck at converting a string into a date.
My code is:
//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());
At some point i;m trying to retrieve the date from the database:
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?
Can you please point me to the correct solution?
Unfortunately the date from the database is retrieved as a String and i can’t change that to another type. So i need to convert that string into Date().
EDIT:
Exception is :
java.text.ParseException: Format.parseObject(String) failed
at java.text.Format.parseObject(Unknown Source)
at main.Program.main(Program.java:20)
I would suggest using Joda Time API for your data and time related operation in Java. Handling
timezoneand all related conversion nuances are pretty easy using this API.