将String转换为Date

时间:2011-05-12 05:33:50

标签: java parsing datetime simpledateformat

我想将以下字符串转换为日期类型

Date dateToFormat = null;

DateFormat formatter = new SimpleDateFormat("E MMM d HH:mm:ss zzzz yyyy"); 

String databaseDateAsString = "Wed May 11 16:30:00 Asia/Calcutta 2011";

try {
    dateToFormat = formatter.parse(databaseDateAsString);
} catch (Exception e) {
    System.out.println("Cannot Parse Date:" + e);
}

但它出现以下错误: -

Cannot Parse Date:java.text.ParseException: Unparseable date: 
        "Wed May 11 16:30:00 Asia/Calcutta 2011"

Plz帮助我如何删除此错误。

1 个答案:

答案 0 :(得分:3)

不允许使用您所使用的时区格式(请阅读javadocs)。如果可能,请将其保留,解析其余部分,在dateFormat对象本身中设置时区

public static void main(String[] args) {
    Date dateToFormat = null;

    DateFormat formatter = new SimpleDateFormat("E MMM d HH:mm:ss yyyy"); // zzzz yyyy");

    String databaseDateAsString = "Wed May 11 16:30:00 Asia/Calcutta 2011";
    databaseDateAsString = "Wed May 11 16:30:00 2011";
    formatter.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
    try {
        dateToFormat = formatter.parse(databaseDateAsString);
        System.out.println(dateToFormat);
    } catch(Exception e) {
        System.out.println("Cannot Parse Date:" + e);
    }
}