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.
What is the best way to handle multiple time zones in the application ? The user can select the timezone that they are in. The user can be anywhere in the world. When displaying data the time has to be adjusted to the timezone that the user has selected.
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….
The Calendar class can convert times between timezones, so long as you know what timezone the server and the client use. To avoid problems in the future if you ever move the server, its best to define what the time in the database should be. I prefer to use UTC for this as its standard, but you can use any timezone you wish, so long as its defined and in your documentation so you'll know in the future.
Here's a question that shows how to do it: Date and time conversion to some other Timezone in java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With