java - 如何将 UTC 时间转换为其他时区 ("CST","IST")

标签 java android timezone java-time

在我的 Android 应用程序服务器中将返回一些 UTC 日期,格式如下(yyyy-MM-dd HH:mm:ss) 24 小时,我需要转换这些时间进入用户的时区,例如 CSTIST

我做了以下代码,但我知道它是否正确,请帮助我以正确的方式进行时区转换。

我将 UTC 日期作为 json 字符串并转换为用户的时区格式并显示 Android 端

private static Date utcDate;
private static DateFormat expireFormat = new SimpleDateFormat(
        "yyyy-MM-dd HH:mm:ss");

        try {
            expireFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            utcDate = expireFormat.parse("2014-04-01 10:32:00");
            System.out.println(TimeZone.getDefault().getID());
            expireFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
            System.out.println(expireFormat.format(utcDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }

    output of the code:
    Asia/Calcutta
    2014-04-01 16:02:00

最佳答案

如果重新格式化的字符串确实是您想要得到的,那么总体方法是可行的。

虽然有一些问题

  1. SimpleDateFormat 不是线程安全类。将其设置为服务器内的静态字段是个问题!

  2. 与关于使用静态字段保存中间 Date 对象的 #1 相同。

  3. “CST”是中国标准时间吗?中部标准时间(美国或澳大利亚)?古巴标准时间?三个字母的缩写 TimeZone 通常是个坏消息。如果可能,尽量使用 Olson 姓名或别名。

  4. 这是服务器端还是安卓端?如果它是一个服务器,您可能会受益于用于日期时间处理的新 Java 8 API。

关于java - 如何将 UTC 时间转换为其他时区 ("CST","IST"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22768905/

相关文章:

android - 更新 sdk 和 google-api 后导入 lib google.android.gms "Could not find class"

android - 关于 ALSA 驱动 : How to handle Audio Devices correctly

android - 如何防止我的应用程序获取 TimeZone.getDefault() 的缓存值?

ruby-on-rails - Rails ActiveRecord 不将时间转换为 UTC,而是将未转换的时间保存为 UTC

java - spring mvc 3.0 小型 Web 应用程序不太工作

java - 当一个类为子类和父类(super class)类型的参数提供重载时,哪个优先?

java - 快速java输入\输出流

Java JFrame 布局

android - React Native : Undefined is not a function(evaluating this. Prop ...)

GMT +x 地区的 Android 日历全天 Activity 日期关闭一天