Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get timzone compared to GMT in Android

I need to get the mobile TimeZone comparing to GMT in Android. I only could see one function returns that but as String:

Calendar c = Calendar.getInstance(); 
TimeZone tz = c.getTimeZone();
tz.getID();

This is the description of getID():

Returns the ID of this TimeZone, such as America/Los_Angeles, GMT-08:00 or UTC.

The problem is I need to get that as Integer like +3, -5...

like image 858
Hesham Saeed Avatar asked Mar 11 '26 20:03

Hesham Saeed


2 Answers

You should be able to calculate the difference based on the TimeZone getOffset() value, see http://developer.android.com/reference/java/util/TimeZone.html#getOffset(long)

like image 113
Michael Avatar answered Mar 13 '26 10:03

Michael


public static String getCurrentTimezoneOffset() {

    TimeZone tz = TimeZone.getDefault();  
    Calendar cal = GregorianCalendar.getInstance(tz);
    int offsetInMillis = tz.getOffset(cal.getTimeInMillis());

    String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
    offset = (offsetInMillis >= 0 ? "+" : "-") + offset;

    return offset;
}
like image 37
PuguaSoft Avatar answered Mar 13 '26 09:03

PuguaSoft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!