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?

有帮助吗?

解决方案

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top