java.text.ParseException:无法解析的日期:“Thu Jan 19 2012 08:00 PM”

问题描述 投票:7回答:5

我想解析一个约会。我的字符串日期是“Thu Jan 19 2012 08:00 PM”。我要解析的代码是:

format = new SimpleDateFormat("EEE MMM dd yyyy hh:mm aaa");
this.settDate(new Timestamp((format.parse(sDate)).getTime()));

但是,它不起作用。我怎么解析这个日期?

完整的方法是:

public void saveTask(int iDevice, String description, String sDate) throws ParseException {
    format = new SimpleDateFormat("EEE MMM dd yyyy hh:mm aaa");
    this.setiDeviceId(iDevice);
    this.setsDescription(description);
    this.settDate(new Timestamp((format.parse(sDate)).getTime()));
    DatabaseManager.save(this);
}

例外:

java.text.ParseException: Unparseable date: "Thu Jan 19 2012 01:00 AM"

调试图片:

谢谢!

java date timestamp
5个回答
17
投票

尝试以下代码...经过测试和工作

    String dateStr = "Thu Jan 19 2012 01:00 PM";
    DateFormat readFormat = new SimpleDateFormat( "EEE MMM dd yyyy hh:mm aaa");

    DateFormat writeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
    Date date = null;
    try {
       date = readFormat.parse( dateStr );
    } catch ( ParseException e ) {
        e.printStackTrace();
    }

    String formattedDate = "";
    if( date != null ) {
    formattedDate = writeFormat.format( date );
    }

    System.out.println(formattedDate);

输出是2012-01-19 13:00:00

干杯!!!乐于帮助!!!


5
投票

在这种情况下,请尝试设置美国等语言环境:

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy hh:mm aaa",Locale.US);
format.parse("Thu Jan 19 2012 08:00 PM");

2
投票

你的默认语言环境是什么?由于日期字符串是英语,请尝试使用美国语言环境进行解析:

DateFormat format = new SimpleDateFormat("EEE MMM dd yyyy hh:mm a", Locale.US);

0
投票

确保该值真正达到了该值。在该行上放置一个断点并仔细检查实际值。

正如你在这里看到的http://ideone.com/MBzYn代码完美无缺。


0
投票

//确保你的字符串日期和DateFormat模式相同; //例如你有String date =“2018/07/10 10:00:00”;

                            DateFormat format = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss");

                            // now makesure format has same pattern in this case ""yyyy/MM/dd HH:mm:ss"
© www.soinside.com 2019 - 2024. All rights reserved.