'How to calculate age from date of birth
I have a user registration form where all user data is stored in database.
I am listing all user data in the UI in a member listing page. In there I have to calculate the age of the user based on their date of birth. I tried by calculating using JSTL, but still I am not getting an answer.
This is what I tried:
<fmt:parseDate value="${user.dateofbirth}" var="parseddate" type="date" pattern="yyyy-MM-dd" />
<jsp:useBean id="now" class="java.util.Date" />
<td class="dataField">
<fmt:formatDate value="${parseddate}" type="date" pattern="MMMM dd yyyy "/>
</td>
<c:set var="today" value="<%=new java.util.Date()%>" />
<fmt:parseNumber type="date" value="${today}" />
<td>
<c:out value="${today-parseddate}"></c:out>
</td>
I am new to JSTL. Can anyone please help me with this?
Solution 1:[1]
If anyone here wants to get the difference between two dates in days and want to display it in another column in the JSP you can you can do like this.
<fmt:parseDate value = "${name_of_your_bean.1st_variable}" var = "formatedDate1" type = "date" pattern = "yyyy-MM-dd" />
<jsp:useBean id="start_date" class="java.util.Date" />
<td > <fmt:formatDate value = "${formatedDate1}" type = "date" pattern = "MMMM dd,yyyy"/> </td>
<fmt:parseDate value = "${name_of_your_bean.2nd_variable}" var = "formatedDate2" type = "date" pattern = "yyyy-MM-dd" />
<jsp:useBean id="end_date" class="java.util.Date" />
<td> <fmt:formatDate value = "${formatedDate2}" type = "date" pattern = "MMMM dd,yyyy"/> </td>
// To display in separate column do like this
<td> <fmt:parseNumber type = "number" integerOnly = "true" value = "${(formatedDate2.time - formatedDate1.time)/(1000 * 60 * 60 * 24)}" /> Days </td>
Solution 2:[2]
Here is code that demonstrates how you might do it with JSTL. It is not exactly perfect because I neglected to account for the extra day in a leap year.
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:parseDate value="1979-09-27" var="parsedDate" type="date" pattern="yyyy-MM-dd" />
<jsp:useBean id="now" class="java.util.Date" />
<fmt:parseNumber type="number" integerOnly = "true"
value="${(now.time - parsedDate.time)/(1000 * 60 * 60 * 24 * 365)}" />
Anyway, it outputs 42 years.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | SnIpEr ReLoAdEd |
Solution 2 | rickz |