0

I am facing an error trying to parse dates with this format:

26-March-2001 15-August-2001

I am using the next code:

    private void parseDate(String firstDate) {
        Date fDate = null;
        try {
            fDate = new SimpleDateFormat("dd-MMM-yyyy").parse(firstDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

But I am getting the error message: Unparseable date: "15-August-2001". I am not pretty sure what date format I have to use.

Thanks

2
  • 1
    try adding 4M (July/August) instead of 3M (Jul/Aug). so to get the full spelt out month, MMMM is what you are looking for Commented Jul 31, 2019 at 16:38
  • 1
    FYI, the terribly troublesome date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle. Commented Jul 31, 2019 at 17:02

2 Answers 2

2

tl;dr

LocalDate
.parse(
    "15-August-2001" , 
    DateTimeFormatter.ofPattern( "dd-MMMM-uuuu" , Locale.US )
)
.toString()

Tip: Better to exchange date-time data textually using only the standard ISO 8601 formats.

java.time

The Answer by Deadpool, while technically correct, is outdated. The modern approach uses the java.time classes that supplanted the legacy date-time classes with the adoption of JSR 310.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.

DateTimeFormatter

Define a custom formatting pattern with DateTimeFormatter.ofPattern. The formatting codes are not entirely the same as with the legacy SimpleDateFormat class, so be sure to study the Javadoc carefully.

Specify a Locale to determine the human language to use in translating the name of the month.

String input = "15-August-2001" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMMM-uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f ) ;

System.out.println( "ld.toString(): " + ld ) ;

See this code run live at IdeOne.com.

ld.toString(): 2001-08-15

Table of date-time types in Java, both modern and legacy.

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

Comments

0

Use Locale.US so that it considers the month names in US format

SimpleDateFormat("dd-MMM-yyyy",Locale.US)

See this code run live at IdeOne.com.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.