为什么此SimpleDataFormat解析在Android上失败? [英] Why does this SimpleDataFormat parsing fail on Android?

查看:81
本文介绍了为什么此SimpleDataFormat解析在Android上失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy");

sdf.parse("Sun Dec 13 10:00:00 UTC 2009")

结果

java.text.ParseException:无法解析的日期:UTC十二月13 10:00:00 2009

java.text.ParseException: Unparseable date: Sun Dec 13 10:00:00 UTC 2009

注意:该代码似乎可以在普通的Java应用程序中运行,但在Android上似乎无法运行.

Note: This code seems to work in a normal Java application but seems to fail on Android.

推荐答案

这不适合我-也许您的默认语言环境使用不同的月份名称?指定格式的语言环境.

It doesn't for me - perhaps your default locale uses different month names? Specify the locale for the format.

// Will definitely work
DateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy",
                                      Locale.US);

// Will definitely not work
DateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy",
                                      Locale.FRANCE);

// Might work - depends on default locale
DateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy")

(问题是一年中的星期几和月份的名称,这显然是特定于文化的.日期和时间分隔符也可能会有所不同.)

(The problem is the names of the days of the week and months of the year, which are obviously culture-specific. Date and time separators can vary too.)

很奇怪,您仍然有问题.只是为了检查,请尝试运行以下简短但完整的程序:

It's odd that you're still having problems. Just to check, please try to run the following short but complete program:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class Test {

    public static void main(String[] args) throws Exception {        
        DateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy",
                                              Locale.US);
        sdf.parse("Sun Dec 13 10:00:00 UTC 2009");
    }
}

如果这不起作用,请尝试取出模式和文本的时区部分.我不知道这是否有问题.

If that doesn't work, try taking out the time zone part of both the pattern and the text. I wonder whether it's having problems with that.

如果Android SimpleDateFormat实现无法解析时区,则可以使用:

If the Android SimpleDateFormat implementation doesn't manage to parse the time zone, you can probably just use:

text = text.replace(" UTC ", " ");
Date parsed = sdf.parse(text);

...当然,已将解析器上的时区设置为UTC.您可能要先检查它是否包含 "UTC",以防万一您的数据格式更改.

... having set the time zone on the parser to UTC, of course. You probably want to check that it contains " UTC " first, just in case your data format changes.

这篇关于为什么此SimpleDataFormat解析在Android上失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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