带有时区的SimpleDateFormat在我的时区中显示日期,如何解决此问题? [英] SimpleDateFormat with timezone displaying dates in my timezone, how do I fix this?

查看:124
本文介绍了带有时区的SimpleDateFormat在我的时区中显示日期,如何解决此问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于这两个日期字符串,我试图创建一个菜单,允许您从两个日期中进行选择(这些日期是从具有用户时区的API返回的):

Given these two date Strings, I am trying to create a menu that allows you to select from the two dates (these are returned from an API with the users timezone):

2019-12-20T00:00:00.000-05:00 2019-12-19T00:00:00.000-05:00

我使用以下代码来解析用户首选时区中的日期字符串(我已将其本地下载到他们的设备中).我已验证TZUtils.getUsersTimeZone()返回此时区: America/New York ,其偏移量为-5.

I use the following code to parse the date string in the users preferred timezone (I have downloaded this locally to their devices). I have verified that the TZUtils.getUsersTimeZone() returns this timezone: America/New York which has an offset of -5.

fun getDateForString(date: String): Date {
        val parser = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
        parser.timeZone = TZUtils.getUsersTimeZone()
        return parser.parse(date)
    }

解析这些日期后,即使我指定使用用户本地时区,它们也将解析为我的本地时间(偏移-6),而不是用户本地时区(-5).创建弹出菜单时,我使用以下代码显示日期

When these dates are parsed, they are parsed into my local time time (offset -6) and not in the users local time zone (-5), even though I specify to use the users local time zone. When I create the popup menu, I used the following code to show the dates

public String getStringForDate(Date date) {
    DateFormat dateFormat = SimpleDateFormat.getDateInstance(DateFormat.SHORT);
    return dateFormat.format(date);
}

这会返回错误的日期以供选择(日期基于我的时区而不是用户).此外,当我从菜单中选择数据时,我用来基于日期是否与所选日期相同来过滤数据的功能不起作用,因为它也使用了我的时区.我该如何解决此问题,或者我只是假设"这对用户有效,因为他们的设备处于其时区中?

And this returns me the wrong dates to select from (the dates are based on my timezone and not the users). Furthermore, when I select the data from the menu, the function I use to filter data based on if it is the same day as the selected date doesn't work because it uses my timezone as well. How do I fix this or do I just "assume" this will work for users since their devices are in their timezones?

推荐答案

您可以改用现代的java.time包,特别是处理时区的 ZonedDateTime .

You can use the modern java.time package instead and specially ZonedDateTime that handles time zones.

String str = "2019-12-20T00:00:00.000-05:00";
ZonedDateTime zonedDateTime = ZonedDateTime.parse(str);

当在用户界面中显示它时,请使用 DateTimeFormatter 将其转换为格式化的字符串

And when showing it in the UI use DateTimeFormatter to convert it to a formatted string

DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME; 

或具有某些自定义格式

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

这将为您提供2种格式

System.out.println(formatter.format(zonedDateTime));

2019-12-20T00:00-05:00
2019-12-20 00:00

2019-12-20T00:00-05:00
2019-12-20 00:00

这篇关于带有时区的SimpleDateFormat在我的时区中显示日期,如何解决此问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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