Getting current date in JSTL EL and doing arithmetic on it
Asked Answered
B

1

17

Without using scriptlets, what's the correct way for doing date arithmetic in JSP?

Here are examples what I'm trying to do:

  1. Get current year (YYYY)
  2. Subtract current year by one to get previous year (YYYY)

Thanks!

Buddha answered 9/2, 2011 at 19:32 Comment(0)
U
54

Use <jsp:useBean> to construct new Date. Use JSTL <fmt:formatDate> to get the year out of it. Use EL to substract it.

<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<jsp:useBean id="now" class="java.util.Date" />
<fmt:formatDate var="year" value="${now}" pattern="yyyy" />
<p>Current year: ${year}</p>
<p>Previous year: ${year - 1}</p>

Result:

Current year: 2011

Previous year: 2010

Note that the pattern for full year is yyyy, not YYYY.

Undervest answered 9/2, 2011 at 19:43 Comment(3)
Thanks a lot! Worked PerfectlyBuddha
BalusC's answers are awesome for the links to the reference materialLuedtke
You might need to use .toString() for {year-1} if you are passing it to .properties file or somewhere else which might add commas(eg: 2,010) considering it a number due to the arithmetic calculation we just did.Predikant

© 2022 - 2024 — McMap. All rights reserved.