Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting current date in JSTL EL and doing arithmetic on it

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!

like image 413
Shawn Avatar asked Feb 09 '11 19:02

Shawn


People also ask

How to get current date in JSTL?

Use <jsp:useBean> to construct new Date . Use JSTL <fmt:formatDate> to get the year out of it. Use EL to substract it. Note that the pattern for full year is yyyy , not YYYY .

How to get current year in JSP?

Java Date getYear() Method The getYear() method of Java date class returns the value by subtracting 1900 from the year that contains or begin with an instant in time which is represented by this date object as interpreted in local time zone.


1 Answers

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.

like image 109
BalusC Avatar answered Sep 24 '22 06:09

BalusC