I am new to Android and I am currently facing an issue to get current time given the timezone.
I get timezone in the format \"GMT-7\" i.e. string. and I have the sys
Set the timezone to formatter, not calendar:
public String getTime(String timezone) {
Calendar c = Calendar.getInstance();
Date date = c.getTime(); //current date and time in UTC
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setTimeZone(TimeZone.getTimeZone(timezone)); //format in given timezone
String strDate = df.format(date);
return strDate;
}
I found a better and simpler way.
First set time zone of app using
TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
And then call Calander to get date internally it uses default timezone set by above through out app.
Calendar cal = Calendar.getInstance();
Log.d("Los angeles time ",cal.getTime().toString());
It will give current time based on time zone.
D/Los angeles time: Thu Jun 21 13:52:25 PDT 2018
Yes, you can. By call TimeZone setDefault()
method.
public String getTime(String timezone) {
TimeZone defaultTz = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone(timezone));
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String strDate = date.toString();
// Reset Back to System Default
TimeZone.setDefault(defaultTz);
return strDate;
}
TimeZone tz = TimeZone.getTimeZone(TimeZoneID);
Calendar c= Calendar.getInstance(tz);
String time=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date(cal.getTimeInMillis()));
TimeZoneID can be one of from below as per as your choice
String[] ids=TimeZone.getAvailableIDs();
then time can be get as per accepted answer above
String time = String.format("%02d" , c.get(Calendar.HOUR_OF_DAY))+":"+
String.format("%02d" , c.get(Calendar.MINUTE))+":"+
String.format("%02d" , c.get(Calendar.SECOND))+":"+
String.format("%03d" , c.get(Calendar.MILLISECOND));