Get current time in a given timezone : android

2019-01-11 14:04发布

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 system time.

Is there a clean way to get the current time in the above given timezone? Any help is appreciated. Thanks,

edit : Trying to do this :

public String getTime(String timezone) {
    Calendar c = Calendar.getInstance();
    c.setTimeZone(TimeZone.getTimeZone(timezone));
    Date date = c.getTime();
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    String strDate = df.format(date);
    return c.getTime().toString();
}

9条回答
forever°为你锁心
2楼-- · 2019-01-11 14:14

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;
}
查看更多
劫难
3楼-- · 2019-01-11 14:15

I got it to work like this :

TimeZone tz = TimeZone.getTimeZone("GMT+05:30");
Calendar c = Calendar.getInstance(tz);
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));
查看更多
甜甜的少女心
4楼-- · 2019-01-11 14:17

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;
}
查看更多
干净又极端
5楼-- · 2019-01-11 14:18

Try this:

SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setTimeZone(TimeZone.getTimeZone("YOUR_TIMEZONE"));
String strDate = df.format(date);

YOUR_TIMEZONE may be something like: GMT, UTC, GMT-5, etc.

查看更多
6楼-- · 2019-01-11 14:18

Cleanest way is with SimpleDateFormat

SimpleDateFormat = SimpleDateFormat("MMM\nd\nh:mm a", Locale.getDefault())

or you can specify the Locale

查看更多
乱世女痞
7楼-- · 2019-01-11 14:19

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 throught 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

查看更多
登录 后发表回答