【问题标题】:Android Server Response time variable' s Time zone change to device location's Time zoneAndroid 服务器响应时间变量的时区更改为设备位置的时区
【发布时间】:2021-12-12 02:13:13
【问题描述】:
  fun getFormatFromISO(iso: String, pattern: String): String {
    var res: String? = ""
    val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH)
    formatter.timeZone= TimeZone.getTimeZone("UTC")
    return try {
        val date = formatter.parse(iso)
      val timeFormat = SimpleDateFormat(pattern, Locale.getDefault())
        timeFormat.timeZone= TimeZone.getDefault() // to convert to devices timezone
        res=timeFormat.format(date)
        res
    } catch (var6: ParseException) {
      "ERR"
    }
  }

我正在尝试将 Api 的响应变量更改为当前设备的时间戳,以便将其用作一些“textview.text”。使用“TimeZone.getDefault()”的部分,假设将UTC时区更改为设备时区。但它没有改变,而是解析UTC转换时间。

在参数'pattern'中传递“H”、“mm”,在参数'iso'中传递类似“2021-10-26T07:22:37Z”的东西

结果是:

日期值为“美国东部时间 10 月 26 日星期二 06:27:18” 资源是 06 ||分辨率为 27

要求的结果是 res 值在设备的时区中。

【问题讨论】:

    标签: android datetime timezone simpledateformat timestamp-with-timezone


    【解决方案1】:

    使用“TimeZone.getDefault()”的部分,假设是 将 UTC 时区更改为设备的时区。

    你的理解是错误的。 TimeZone.getDefault() 返回服务器的TimeZone,而不是设备。

    解决方案:

    有许多网络服务(以下列表中提供了一些链接),您可以使用它们获取设备所在的时区。一旦你有了时区,你就可以在你的代码中使用它。

    1. How to get Latitude and Longitude of the mobile device in android?
    2. How to get a time zone from a location using latitude and longitude coordinates?
    3. Android get device locale

    切换到java.time

    java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,改用modern Date-Time API*

    演示:

    import java.time.Instant;
    import java.time.ZoneId;
    import java.time.format.DateTimeFormatter;
    import java.util.Locale;
    
    public class Main {
        public static void main(String[] args) {
            // Test
            System.out.println(getFormattedDateTimeInDeviceTz("2021-10-26T18:12:20.698134Z", "uuuu-MM-dd'T'HH:mm:ssXXX"));
        }
    
        static String getFormattedDateTimeInDeviceTz(String iso, String pattern) {
            Instant instant = Instant.parse(iso);
    
            // Get the date-time in the device's timezone e.g. Asia/Kolkata
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH);
            return instant.atZone(ZoneId.of("Asia/Kolkata")).format(dtf);
        }
    }
    

    输出:

    2021-10-26T23:42:20+05:30
    

    ONLINE DEMO

    注意:我在演示代码中使用了Locale.ENGLISH。使用上面列表中的第三个链接更改它。请注意,Locale.getDefault() 返回的是服务器的 Locale,而不是设备。

    通过 Trail: Date Time 了解有关现代日期时间 API 的更多信息。


    * 如果您正在为一个 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring。请注意,Android 8.0 Oreo 已经提供了support for java.time

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 1970-01-01
      • 2014-04-19
      • 1970-01-01
      • 2020-12-12
      • 2013-07-21
      • 2020-04-11
      • 2012-11-03
      • 2015-04-23
      相关资源
      最近更新 更多