Karan
Karan

Reputation: 497

convert String to Date

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.

Upvotes: 0

Views: 605

Answers (1)

MJB
MJB

Reputation: 9389

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

Upvotes: 3

Related Questions