66

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?

Mike G
  • 4,232
  • 9
  • 40
  • 66
Ashish Augustine
  • 1,784
  • 4
  • 20
  • 50
  • 1
    If you use `JodaTime`, you can use `DateTime.now( DateTimeZone.getDefault() );`. If you're not using `JodaTime`, you should check it out. – Joshua Pinter Jul 19 '14 at 18:54

4 Answers4

134

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()
Ramin Bateni
  • 16,499
  • 9
  • 69
  • 98
John
  • 8,846
  • 8
  • 50
  • 85
31
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));
Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
18

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);
timv
  • 3,346
  • 4
  • 34
  • 43
  • 5
    This won't work for timezones that fall under half hour differences such as Newfoundland which is GMT-2:30, you would simply get 2 back – pkramaric Apr 07 '16 at 04:42
-10

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);
Aditi Parikh
  • 1,522
  • 3
  • 13
  • 34