Getting current date in JSTL EL and doing arithmetic on it

ⅰ亾dé卋堺 提交于 2020-07-29 09:14:48

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/4949554/getting-current-date-in-jstl-el-and-doing-arithmetic-on-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!