获取给定时区的当前时间:android

2022-09-02 02:15:51

我是Android的新手,目前我面临着一个问题,即在给定时区的情况下获取当前时间。

我以“GMT-7”格式获得时区,即字符串。我有系统时间。

有没有一种干净的方法来获取上述给定时区的当前时间?任何帮助是值得赞赏的。谢谢

编辑 : 尝试这样做 :

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();
}

答案 1

我让它像这样工作:

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));

此外,基于此日期的所有其他时间转换也应与此时区一起使用,否则将使用设备的默认时区,并且时间将基于该时区进行转换。


答案 2
// Backup the system's timezone
TimeZone backup = TimeZone.getDefault();

String timezoneS = "GMT-1";
TimeZone tz = TimeZone.getTimeZone(timezoneS);
TimeZone.setDefault(tz);
// Now onwards, the default timezone will be GMT-1 until changed again

Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String timeS = String.format("Your time on %s:%s", timezoneS, date);
System.out.println(timeS);

// Restore the original timezone
TimeZone.setDefault(backup);
System.out.println(new Date());

推荐