-1

I am trying to simply pass a date and parse it using simpledateformat. But instead of printing the correct value, it's printing wrong date.

public static void main(String[] args) {
    getAge("29-02-2016");
}

public static void getAge(String dob1) {
    DateFormat format = new SimpleDateFormat("dd-mm-yyyy");
    try {
        Date dob = format.parse(dob1);
        System.out.println(dob);
        Calendar realDob = Calendar.getInstance();
        realDob.setTime(dob);
        System.out.println(realDob.get(Calendar.YEAR));
        Calendar today = Calendar.getInstance();

        int age = today.get(Calendar.YEAR) - realDob.get(Calendar.YEAR);
        if(age >=18) {
            System.out.println("18 years");
        } else {
            System.out.println("Underage");
        }

    } catch (ParseException e) {
        e.printStackTrace();
    }
}

its printing : Fri Jan 29 00:02:00 IST 2016 but it should be February

halfer
  • 19,824
  • 17
  • 99
  • 186
  • This same error gets asked about weekly. – Hovercraft Full Of Eels Dec 06 '17 at 15:52
  • `mm` means minutes. Always, always, always read the documentation for `SimpleDateFormat` carefully when it's not behaving as you expect. – Jon Skeet Dec 06 '17 at 15:53
  • [Sample Google search for similar questions](https://www.google.com/search?q=site%3Astackoverflow.com+java+simpledateformat+month+wrong) -- please check this out, and consider using a similar search prior to asking. – Hovercraft Full Of Eels Dec 06 '17 at 15:54
  • 1
    The `SimpleDateFormat` class is not only long outdated, it is also notoriously troublesome. I strongly recommend you throw it out, and its old-fashioned friends `Date` and `Calendar` too. [`java.time`, the modern Java date and time API also known as JSR-310](https://docs.oracle.com/javase/tutorial/datetime/), is much nicer to work with. Furthermore, if you made the same error with the modern API, it would tell you you were wrong. I consider this already an improvement over giving you a wrong result and pretending everything is well. – Ole V.V. Dec 06 '17 at 16:09
  • As an aside, your code snippet seems to accept a person as 18 if s/he is born in 1999, no matter if his/her birthday comes later in the year. While this may not be a big deal this late in the year, it may matter in January when you start accepting everyone born in 2000. – Ole V.V. Dec 06 '17 at 16:12

1 Answers1

1

mm is for minutes, use MM: DateFormat format = new SimpleDateFormat("dd-MM-yyyy");

alper
  • 322
  • 2
  • 14