gpt4 book ai didi

java - 解析时区为 "Etc/GMT"的日期

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:33:03 24 4
gpt4 key购买 nike

我的第一次尝试是:

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
Date date = formatter.parse(string);

它抛出 ParseException,所以我发现了这个 hack:

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
TimeZone timeZone = TimeZone.getTimeZone("Etc/GMT");
formatter.setTimeZone(timeZone);
Date date = formatter.parse(string);

它也不起作用,现在我被卡住了。如果我只是将时区更改为“GMT”,它可以毫无问题地解析。

编辑:要解析的示例字符串为“2011-11-29 10:40:24 Etc/GMT”

edit2:我不想完全删除时区信息。我正在编写一个从外部用户接收日期的服务器,因此其他日期可能会有其他时区。更准确地说:我收到的这个具体日期是在 iPhone 应用程序上进行应用程序内购买后来自苹果服务器的收据,但我也可以从其他来源收到日期。

最佳答案

不知道这个问题是否仍然与你相关,但如果你使用 Joda 时间,这会起作用:

DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss ZZZ").parseDateTime(s)

在没有 Joda 时间的情况下,以下内容将起作用(尽管需要更多工作):

String s = "2011-11-29 10:40:24 Etc/GMT";

// split the input in a date and a timezone part
int lastSpaceIndex = s.lastIndexOf(' ');
String dateString = s.substring(0, lastSpaceIndex);
String timeZoneString = s.substring(lastSpaceIndex + 1);

// convert the timezone to an actual TimeZone object
// and feed that to the formatter
TimeZone zone = TimeZone.getTimeZone(timeZoneString);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(zone);

// parse the timezoneless part
Date date = formatter.parse(dateString);

关于java - 解析时区为 "Etc/GMT"的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8324069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com