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

rasilvap
  • 1,771
  • 3
  • 31
  • 70
  • 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 – Angel Koh Jul 31 '19 at 16:38
  • 1
    FYI, the terribly troublesome date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jul 31 '19 at 17:02

2 Answers2

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98