【发布时间】:2020-05-11 16:22:12
【问题描述】:
我正在尝试制作一个天气预报应用程序,并且我从 api 获得了一个 UTC 时间戳:OpenWeatherMap。我通过创建 Date 对象将其转换为日期。例如,对于 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;
}
【问题讨论】:
-
您的目标是哪个 API 级别?无论如何,您应该使用
java.time包中的类。然后,您可以简单地使用Instant.ofEpochSecond获得Instant,然后可以将其转换为OffsetDateTime,然后可以使用DateTimeFormatter对其进行格式化。
标签: java android android-studio date utc