Friday, December 2, 2011

Calculating Age from Date of Birth in Java /JSP

 <%@page import="java.text.DateFormat"%>
<%@page import="java.text.SimpleDateFormat"%>

<%
            String dob = "1986-06-24"; (YYYY-MM-DD)

            int yearDOB = Integer.parseInt(dob.substring(0, 4));
            int monthDOB = Integer.parseInt(dob.substring(5, 7));
            int dayDOB = Integer.parseInt(dob.substring(8, 10));

            DateFormat dateFormat = new SimpleDateFormat("yyyy");
            java.util.Date date = new java.util.Date();
            int thisYear = Integer.parseInt(dateFormat.format(date));

            dateFormat = new SimpleDateFormat("MM");
            date = new java.util.Date();
            int thisMonth = Integer.parseInt(dateFormat.format(date));

            dateFormat = new SimpleDateFormat("dd");
            date = new java.util.Date();
            int thisDay = Integer.parseInt(dateFormat.format(date));

            int age = thisYear - yearDOB;


            if (thisMonth < monthDOB) {
                age = age - 1;
        }

          if (thisMonth == monthDOB && thisDay < dayDOB) {
                age = age - 1;
        }
           
%>

<%=age%>

6 comments:

  1. Thank you so so much for this code... Its solved a really really big problem in my code...Thanks once again..

    ReplyDelete
  2. Thank you so much for the code you had provided and it helped me alot

    ReplyDelete
  3. An error occurred at line: 5 in the jsp file: /jsp/d.jsp
    The left-hand side of an assignment must be a variable
    <%@page import="java.text.SimpleDateFormat"%>
    this error is coming

    ReplyDelete
  4. I got a exception of NumberFormatException. The date is in String which cannot be converted to Integer.

    ReplyDelete