3

I can't seem to see the problem with the example code below. For some reason seems to be ignoring the year and saying the dates are the same, as can be seen in the output below. I must be missing something simple.

01/28/2006
01/16/2007
Tue Apr 01 00:00:00 PDT 2008
Tue Apr 01 00:00:00 PDT 2008
done

import java.util.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

    class ExampleProgram {
      public static void main(String[] args){
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        String d1String = "01/28/2006";
        String d2String = "01/16/2007";
        System.out.println(d1String);
        System.out.println(d2String);
        Date d1=null;
        try {
            d1 = df.parse(d1String);
        } catch (ParseException e) {                
            System.out.println(e.getMessage());
        }           
        Date d2=null;
        try {
            d2 = df.parse(d2String);
        } catch (ParseException e) {                
            System.out.println(e.getMessage());
        }
        System.out.println(d1);
        System.out.println(d2);
        System.out.println("done");
      }
    }
1
  • An April fools joke? It just seems very contrived that the dates BOTH correspond to April 1. + 1 year, -12 months == same date. If your dateformat object is strict (df.setLenient(false)) then it would raise the error for you. Commented Apr 14, 2009 at 4:31

4 Answers 4

6
"dd/MM/yyyy"

should read:

"MM/dd/yyyy"
Sign up to request clarification or add additional context in comments.

Comments

2

As Peter mentioned, the meaning of the letters can be found in the documentation here: https://docs.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html.

Comments

1

The reason that it wasn't giving you what you expected is like Peter said the SimpleDateFormat should read "MM/dd/yyyy"

The reason that the result is saying that they appear to be equal is because with the format that you've given it "dd/MM/yyyy", d1String's Month is 28. It is taking 28 - 12, adding a year, 16 - 12, adding another year, and the result is 4 (April) and the year is now 2008. Same thing for d2String.

Comments

0

You could try declaring your dates as Date objects.

1 Comment

He did. The constructor Date(String) is deprecated. He's using the correct way to convert a String into a Date.

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.