I need to save the phone's timezone in the format [+/-]hh:mm
I am using TimeZone class to deal with this, but the only format I can get is the following:
PST -05:00
GMT +02:00
I would rather not substring the result, is there any key or option flag I can set to only get the value and not the name of that timezone (GMT/CET/PST...)?
No, you don't. Offset on its own is not enough, you need to store the whole time zone name/id. For example I live in Oslo where my current offset is +02:00 but in winter (due to dst) it is +01:00. The exact switch between standard and summer time depends on factors you don't want to explore.
So instead of storing
+ 02:00
(or should it be+ 01:00
?) I store"Europe/Oslo"
in my database. Now I can restore full configuration using:Want to know what is my time zone offset today?
However the same in December:
Enough to say: store time zone name or id and every time you want to display a date, check what is the current offset (today) rather than storing fixed value. You can use
TimeZone.getAvailableIDs()
to enumerate all supported timezone IDs.With java8 now, you can use
to get the current system time offset from UTC. Then you can convert it to any format you want. Found it useful for my case. Example : https://docs.oracle.com/javase/tutorial/datetime/iso/timezones.html
@MrBean - I was in a similar situation where I had to call a 3rd-party web service and pass in the Android device's current timezone offset in the format +/-hh:mm. Here is my solution:
will give you a standardized string representation like "+0300"
I know this is old, but I figured I'd give my input. I had to do this for a project at work and this was my solution.
I have a Building object that includes the Timezone using the TimeZone class and wanted to create zoneId and offset fields in a new class.
So what I did was create:
Then in the constructor I passed in the Building object and set these fields like so:
So timeZoneId might equal something like "EST" And timeZoneOffset might equal something like "-05:00"
I would like to not that you might not
We can easily get the millisecond offset of a
TimeZone
with only aTimeZone
instance andSystem.currentTimeMillis()
. Then we can convert from milliseconds to any time unit of choice using theTimeUnit
class.Like so:
Or if you prefer the new Java 8 time API