Suppose that my server located in USA and I live in Russia. We know that they have different time zones.
My application getting text(String
) from server. And this text data has Date
column in database to keep record date.
When I get data, I also get date
knowledge. So I can group them by time. First ones at the top and last ones at the bottom. Whatever...
I wrote a function to show date value more human-readable such as "13 hours", "9 minutes". Server sends me the date in server's (USA) time zone.
When I calculate time on application with Russia time zone (because it's current time zone on application), it calculates wrong. So, it's not stuff what anybody wants.
What should I do to achieve the correct calculation?
Annotation: This application will be used by different countries' citizens. So I can't make the calculation static.
There isn't really such as thing as "Russia time zone" or "USA time zone". Both of those countries have several different time zones. See the Wikipedia articles on Time in Russia and Time in the USA.
You should always write server code such that it is not dependent on the time zone that the server is running in. Usually this is done by storing all time as UTC. Since the client is an Android device, just convert to and from local time on the client, sending just UTC to/from the server.
If you're working in Java, you should probably use Joda Time for your conversions. It is much cleaner and easier to use than the Calendar
class.
Update
As Basil pointed out in comments, the Joda-Time project is now in maintenance mode. The team advises migration to the java.time
classes defined by JSR 310. For earlier Android, see the ThreeTen-Backport and ThreeTenABP projects. See How to use….