convert String to Date

送分小仙女□ 提交于 2019-12-11 20:00:53

问题


I want to convert the following string into Date type this way

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);
}

But it is giving the following error:-

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

Plz help how can I remove this error.


回答1:


The timezone format you are using is not allowed (read the javadocs). If possible, leave it out, parse the rest, setting the timezone in the dateFormat object itself

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);
    }
}


来源:https://stackoverflow.com/questions/5973692/convert-string-to-date

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