0

I am getting date from database from time-zone A (dBDate) and I am getting the current date from my android device I am currently using in time-zone B (deviceNowDate), I need to find the difference between the 2 dates in milli seconds so I think I should convert both of these dates to 1 hardcoded timezone (say timezone C) and then find the difference. How do I convert both of these dates to another time zone?

They are calendar objects.

dbDate.setTimeZone();

will this change the time zone and also convert the date/time for me?

Akshat Agarwal
  • 2,837
  • 5
  • 29
  • 49
  • If both date from DB and your device already in `Calendar` instance with correct timezone set, then I think you can just use `Calendar.getTimeInMillis()` to get the current time as UTC milliseconds from the epoch. – Andrew T. Oct 30 '13 at 14:13
  • thats the problem, my DB is using America/New_York time zone however my device is in EST time zone – Akshat Agarwal Oct 30 '13 at 14:19
  • How do you store the date in DB? Is it in UTC milliseconds? Or text format? `setTimeZone()` only change the timezone representation of the `Calendar`. (e.g. from `2013-10-30T00:00:00-03:00` to `2013-10-30T02:00:00-01:00`) – Andrew T. Oct 30 '13 at 15:05

1 Answers1

2

Since the date stored in the database is already in UTC, you can just use the value right away. Or the alternative way is to get a Calendar instance and set the time in milliseconds using setTimeInMillis(long millis).

For the current date & time on the device, invoking Calendar.getInstance() will return a Calendar with device's time zone, date and time.

The getTimeInMillis() will return the UTC milliseconds from epoch, which is independent of the time zone.

Try

long dbMillis = ... // get date value from DB, in UTC already

Calendar cal = Calendar.getInstance(); // get device's date time with
                                       // default device time zone
long now = cal.getTimeInMillis(); // returns device's date time in UTC

long diff = Math.abs(now - dbMillis);
Andrew T.
  • 4,701
  • 8
  • 43
  • 62