Jamie Studzinski
Jamie Studzinski

Reputation: 49

Converting a String of a Date to a Date

I'm having troubles converting a String of a date entered by a user to an actual Date that can be sent to a database.

Ultimately the user enters a date in the format of YYYY-MM-DD and it gets sent to the database. I'm trying this:

String date = "2015-03-02";
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
Date parsedDate = sdf.parse(date);

this is all it outputs

Sun Dec 28 00:00:00 CST 2014

Upvotes: 0

Views: 57

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201527

Your format String should be yyyy-MM-dd; and something like

String date = "2015-03-02";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
    Date parsedDate = sdf.parse(date);
    System.out.println(sdf.format(parsedDate));
} catch (ParseException e) {
    e.printStackTrace();
}

Output is

2015-03-02

Upvotes: 1

Related Questions