为什么我从 UTC 时间戳转换时总是得到错误的 date/time?

Why do I keep getting the wrong date/time when converting from a UTC timestamp?

我正在尝试制作一个天气预报应用程序,我从 api: OpenWeatherMap 获得了一个 UTC 时间戳。我通过创建日期对象将其转换为日期。例如,对于 UTC 时间戳 1589220000,UTC 时间是 5 月 11 日下午 6 点。我做这个转换,我总是得到 5 月 11 日下午 2 点。巧合的是,我确实住在一个时间比 UTC 晚 4 小时的地方,但是当我使用假 gps 位置转换器测试我的应用程序时,我仍然得到 5 月 11 日下午 2 点。这表明 Android 没有根据我当前的位置创建日历,因为例如迪拜的时区不晚 4 小时。

这是我的代码:

public String convertDate(long unixTimeStamp) throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat("EEEE, MMM d, h:mm aaa");
        Date date = new Date(unixTimeStamp*1000 );
        String nowDate = dateFormat.format(date);

        return nowDate;
    }

帮自己一个忙,使用 java.time.* 而不是 Date/SimpleDateFormat

如果您不能使用 API 26/Gradle 4.x 或更高版本(因此可以访问 Java 8),则使用,直到可以,https://www.threeten.org/threetenbp/ which you can use on Android via Jake Wharton's adaptation: https://github.com/JakeWharton/ThreeTenABP

要转换自纪元以来的瞬间时间:

    val instant = Instant.ofEpochMilli(milliseconds)

    val result = instant.atOffset(ZoneOffset.UTC).toLocalDateTime() //for example

有很多方法可以尝试。

不要忘记为要加载的时区数据库初始化库。在您的 Application class 中,将此添加到 onCreate():

    AndroidThreeTen.init(this)

要格式化您的日期,您可以继续上面的"result":

val result = ...
result.format(DateTimeFormatter...)

DateTimeFormatter 辅助函数很多,看文档,很容易上手。

其中之一是ofPattern(...):

DateTimeFormatter
   .ofPattern("EEEE, MMM d, h:mm aaa")
   .withLocale(Locale.US) // you can use systemDefault or chose another

天空,是极限。

您没有在 SimpleDateFormat 上设置时区,因此您将获得 JVM 的默认时区:

dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

Demo