0

I ma getting exeception while parsing the date.

following is the code:

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD");
    Date d = format.parse("2014/02/20");
    System.out.println(d);
2
  • your date pattern is different and also replace DD with dd.Check Commented Apr 27, 2015 at 10:43
  • initialize your formatter like new SimpleDateFormat("yyyy/MM/dd") Commented Apr 27, 2015 at 10:48

3 Answers 3

3

Not only have you got the slashes/dashes wrong, you're also using DD (day of year) instead of dd (day of month). You want:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

As always, read the documentation to find out exactly what pattern symbols mean - and if you find it's behaving oddly, check the pattern against the data very carefully.

I would also recommend:

  • Using Joda Time (pre-Java-8) or java.time (Java 8) if you possibly can; the java.util.Date/Calendar API is horrible
  • Specifying the locale explicitly
  • Specifying the time zone explicitly

Currently you're using the default time zone and locale. While the locale may not matter in this case (unless it's used to pick the calendar system; I can't remember offhand) I think it's clearer to explicitly specify it. The time zone definitely matters; if you only ever want to treat this as a date (no time) it's probably worth specifying UTC - that way it's easy to interoperate with anything else, and you get day boundaries in obvious places in the underlying millisecond representation.

Sign up to request clarification or add additional context in comments.

1 Comment

Just realized the second issue... :D
1

Your dateformat doesn't match your string.

Date d = format.parse("2014-02-20");

or

SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");

2 Comments

DD is for day in a year (this is not me who downvoted)
@SashaSalauyou Thanks for correction, did not notice that.
0

java.time

In modern Java, use LocalDate class to represent a date-only value, without time-of-day, and without time zone or offset-from-UTC.

Replace the / separators with - to comply with ISO 8601 standard format.

LocalDate ld = LocalDate.parse( "2014/02/20".replace( "/" , "-" ) ) ;

Or define a formatter.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu/MM/dd" ) ;
LocalDate ld = LocalDate.parse( "2014/02/20" , f ) ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.