Dan Dinu
Dan Dinu

Reputation: 33438

Difference between two dates with different timezones

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)

Upvotes: 0

Views: 398

Answers (2)

Sujay
Sujay

Reputation: 6783

I would suggest using Joda Time API for your data and time related operation in Java. Handling timezone and all related conversion nuances are pretty easy using this API.

Upvotes: 2

Brighton Vino
Brighton Vino

Reputation: 395

You should specify a DateFormat to match the string format being received

Eg.

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

Once you have the both the dates in required format, then apply the date arithmetic operations

Other Format Specifiers for DateString can be found in http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Upvotes: 0

Related Questions