Getting the current time zone in android application
JavaAndroidJava 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);