Android SimpleDateFormat fails to parse datetime (works fine on sun 1.6 jre)

不羁岁月 提交于 2019-12-24 10:52:13

问题


Any ideas why the followng fails on Android 2.2...

java.text.ParseException: Unparseable date: 2011-02-16 11:38:03.328 UTC

...while it works fine on a sun JRE 1.6 ?

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
    try
    {
      Date date = dateFormat.parse("2011-02-16 11:38:03.328 UTC");
    }
    catch (ParseException e)
    {
      e.printStackTrace();
    }

As mentioned ion Comment, can make the test even simpler:

new SimpleDateFormat("z").parse("UTC")

This throws a parse exception. I am using a nexus one device, android 2.2


回答1:


Use this instead

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");



回答2:


I have a workaround now:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S 'UTC'");
try
{
  Date date = dateFormat.parse("2011-02-16 11:38:03.328 UTC");
}
catch (ParseException e)
{
  e.printStackTrace();
}

This allows me to at least parse the date in Android 2.2. My application has been modified to try "yyyy-MM-dd HH:mm:ss.S 'UTC'" and then try "yyyy-MM-dd HH:mm:ss.S z" if the first parse fails

Thanks for all answers




回答3:


Try specifying the locale like this:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z", Locale.ENGLISH);



回答4:


I have copied this code and got casting exception...

try this code of mine

java.text.SimpleDateFormat format = new SimpleDateFormat(
                    "dd-MM-yyyy");
            java.util.Calendar cal = Calendar.getInstance(new SimpleTimeZone(0,
                    "GMT"));
            format.setCalendar(cal);
java.util.Date date = null;
            try {
                date = format.parse(EditProfile.dateOFBirth);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

I hope this help you



来源:https://stackoverflow.com/questions/5016582/android-simpledateformat-fails-to-parse-datetime-works-fine-on-sun-1-6-jre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!