时区显示值与给定时区的 GMT 偏移量? [英] Timezone display value with GMT offset from a given timezone?

查看:59
本文介绍了时区显示值与给定时区的 GMT 偏移量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个时区列表来显示给用户选择.显示名称必须是这样的:

I would like to construct a timezone list to show it to users to select. The display name has to be like:

( GMT 5:30 ) 印度标准时间(亚洲/加尔各答)

我正在使用 TimeZone.getAvailableIDs() 获取所有时区并构建列表.我写的代码是:

I am taking all timezones with TimeZone.getAvailableIDs() and constructing the list. The code I wrote is:

String[] timeZones = TimeZone.getAvailableIDs();
List<String> tzList = new ArrayList<String>();
for (String timeZone : timeZones)
{
  TimeZone tz = TimeZone.getTimeZone(timeZone);
  StringBuilder timeZoneStr = new StringBuilder();
  timeZoneStr.append("( GMT ").append(tz.getRawOffset() / (60 * 60 * 1000)).append(" ) ").append(tz.getDisplayName()).append("(").append(timeZone).append(")");
  tzList.add(timeZoneStr.toString());
  System.out.println(timeZoneStr.toString());
}

输出片段如下:

( GMT 5 ) Maldives Time(Indian/Maldives)
( GMT 5 ) Pakistan Time(PLT)
( GMT 5 ) India Standard Time(Asia/Calcutta)
( GMT 5 ) India Standard Time(Asia/Kolkata)
( GMT 5 ) India Standard Time(IST)

但我需要得到的输出是:

But the output I need to get is:

( GMT 5:0 ) Maldives Time(Indian/Maldives)
( GMT 5:0 ) Pakistan Time(PLT)
( GMT 5:30 ) India Standard Time(Asia/Calcutta)
( GMT 5:30 ) India Standard Time(Asia/Kolkata)
( GMT 5:30 ) India Standard Time(IST)

我该怎么做才能到达 5:30?

What should I do to get 5:30?

推荐答案

一个更具可读性的答案如下:

A more readable answer is the following:

for (String timeZone : timeZones) {
  TimeZone tz = TimeZone.getTimeZone(timeZone);

  long hours = TimeUnit.MILLISECONDS.toHours(tz.getRawOffset());
  long minutes = TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset())
      - TimeUnit.HOURS.toMinutes(hours);

  String timeZoneString = String.format("( GMT %d:%02d ) %s(%s)", hours,
      minutes, tz.getDisplayName(), timeZone);
  tzList.add(timeZoneString);
  System.out.println(timeZoneString);
}

这也可以正确显示,例如5:005:30.String.format() 的使用使得在阅读代码时更容易确定最终字符串.TimeUnit 类简化了数学.

This also correctly displays e.g. 5:00 and 5:30. The use of String.format() makes the final string easier to determine when reading the code. The use of the TimeUnit class simplifies the maths.

这篇关于时区显示值与给定时区的 GMT 偏移量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆