David
David

Reputation: 1101

Java date parsing specific format

I wrote a little piece of code to expose my problem.

public class date {
    public static void main(String args[]) {
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy",Locale.ENGLISH);
        System.out.println("The date format is : dd-MM-yyyy.");
        String date1 = "20-06-2012";
        System.out.println("The date1 is : " + date1);
        String date2 = "2012-06-20";
        System.out.println("The date2 is : " + date2);
        try {
            System.out.println(formatter.parse(date1).toString());
            System.out.println(formatter.parse(date2).toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

The output looks like so :

The date format is : dd-MM-yyyy.
The date1 is : 20-06-2012
The date2 is : 2012-06-20
Wed Jun 20 00:00:00 EDT 2012
Mon Dec 03 00:00:00 EST 25

The problem is that I want to have an error raised when the date submitted doesn't match the pattern specified in the SimpleDateFormat, unfortunately, it looks like it sees numbers at the correct position in the string separated by the dashes so it makes it through. Is there another tool to do this or am I wrongly using SimpleDateFormat?

Upvotes: 2

Views: 349

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 338326

As the other Answers say, you must define a formatter that fits your data.

java.time

Java 8 and later come bundled with the new java.time framework (Tutorial). These new classes supplant the old java.util.Date/.Calendar & java.text.SimpleDateFormat classes that have proven to be so confusing and troublesome. This new framework is inspired by the very successful Joda-Time library, defined by JSR 310, and extended by the ThreeTen-Extra project.

Also, java.time includes a class LocalDate to represent simply a date only without time-of-day and time zone, as you have in the Question.

The formatting patterns are defined in a manner similar to java.text.SimpleDateFormat, but may vary slightly. Be sure to study the doc.

String input = "20-06-2012";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd-MM-yyyy" );
LocalDate localDate = LocalDate.parse( input , formatter );

Dump to console.

System.out.println( "localDate : " + localDate );

When run.

localDate : 2012-06-20

Locale Not Needed Here

The Locale.English is not needed here, as there are no names of months or day-of-weeks in your data to be translated.

For more information about when to use Locale in parsing/generating string representations of date-time values, see When is Locale needed for parsing date-time strings in Java?.

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160181

Use SimpleDateFormat.setLenient(boolean) and set to false to bypass SDF parse heuristics.

Then switch to Joda-Time ;)

Upvotes: 9

Related Questions