Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get previous year from the current one in a JSP page

Tags:

date

jsp

jstl

Seems simple, but not for me. I can get the current year with:

<jsp:useBean id="date" class="java.util.Date" />
<fmt:formatDate value="${date}" pattern="yyyy" />

But I can't do a simple -1 in the resulting value because the operations dies there, as html text. I'd love to -1 the year from that ${date} but, well, it's a date.

I'm looking for a non-scriptlet, preferably JSTL solution. Thank you in advance.


2 Answers

JSTL converts values in the page based on appropriate coercions rules between object and primitives, so this should work:

<jsp:useBean id="date" class="java.util.Date" />
<fmt:formatDate value="${date}" pattern="yyyy" var="currentYear" />

<c:out value="${currentYear}" /> /
<c:out value="${currentYear - 1}" />

Or depending on your JSP version you can directly use ${currentYear} and ${currentYear - 1} without the <c:out>.

like image 141
Bogdan Avatar answered Jan 03 '26 20:01

Bogdan


You can use EL.

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<jsp:useBean id="date" class="java.util.Date" />
<fmt:formatDate var="now" value="${date}" pattern="y" />  
Previous year is ${now - 1}
like image 35
rickz Avatar answered Jan 03 '26 19:01

rickz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!