Getting the current time zone in android application

JavaAndroid

Java Problem Overview


How can I get the current time zone in my Android application? I tried to use this

Calendar cal = Calendar.getInstance( userConfig.locale);
TimeZone tz = cal.getTimeZone();   

But I am not getting the timezone from it. How can I display the timezone?

Java Solutions


Solution 1 - Java

Use this

Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
Log.d("Time zone","="+tz.getDisplayName());

or you can also use the java.util.TimeZone class

TimeZone.getDefault().getDisplayName()

Solution 2 - Java

String timezoneID = TimeZone.getDefault().getID();
System.out.println(timezoneID);

In my Console, it prints Asia/Calcutta

And any Date Format, I set it Like....

SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy");
sdf2.setTimeZone(TimeZone.getTimeZone(timezoneID));

Solution 3 - Java

I needed the offset that not only included day light savings time but as a numerial. Here is the code that I used in case someone is looking for an example.

I get a response of "11" which is what I would expect in NSW,Australia in summer. I also needed it as a string so I could post it to a server so you may not need the last line.

TimeZone tz = TimeZone.getDefault();
Date now = new Date();
int offsetFromUtc = tz.getOffset(now.getTime()) / 3600000;
String m2tTimeZoneIs = Integer.toString(offsetFromUtc);

Solution 4 - Java

To display the current time, you should run below code snippet on the UI thread. This worked for me:

Timer timer = new Timer();          
timer.schedule(new TimerTask() {          
    public void run() {      
        runOnUiThread(new Runnable(){      
            public void run() {      
                dateTxt.setText(new Date().toString());      
            }      
        });      
    }      
}, 0, 1000);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAshish AugustineView Question on Stackoverflow
Solution 1 - JavaJohnView Answer on Stackoverflow
Solution 2 - JavaSamir MangroliyaView Answer on Stackoverflow
Solution 3 - JavatimvView Answer on Stackoverflow
Solution 4 - JavagangeshwariView Answer on Stackoverflow