Reputation: 544
I have to show first date of next and previous month, is there any way I can get it using JSTL. Pure JSTL is preferred.
I could get tomorrow as below.
<jsp:useBean id="ourDate" class="java.util.Date"/>
<jsp:setProperty name="ourDate" property="time" value="${ourDate.time + 86400000}"/>
<fmt:formatDate value="${ourDate}" pattern="dd/MM/yyyy"/>
I couldn't get the first day of month.
Upvotes: 0
Views: 1445
Reputation: 1108802
JSTL has only tags to parse and format the date, not to manipulate the date. Your best resort is EL (those ${}
things). Since Servlet 3.0 / EL 2.2 it supports method expressions in JSP as well. You could then use among others Calendar#set()
and Calendar#add()
methods. True, this is hacky, but as you asked for "pure JSTL", that's best you can get.
<jsp:useBean id="firstDayOfMonth" class="java.util.GregorianCalendar">
${firstDayOfMonth.set(5,1)}
</jsp:useBean>
<jsp:useBean id="firstDayOfPreviousMonth" class="java.util.GregorianCalendar">
${firstDayOfPreviousMonth.set(5,1)}
${firstDayOfPreviousMonth.add(2,-1)}
</jsp:useBean>
<jsp:useBean id="firstDayOfNextMonth" class="java.util.GregorianCalendar">
${firstDayOfNextMonth.set(5,1)}
${firstDayOfNextMonth.add(2,1)}
</jsp:useBean>
(those expressions are merely for self-documentary purposes nested inside the <jsp:useBean>
, they can be placed outside, but it may be more confusing for starters; the first argument (5
resp. 2
) is by the way value of the constant field Calendar.DAY_OF_MONTH
and Calendar.MONTH
)
Now you can present them as below via Calendar#getTime()
the usual way:
<fmt:formatDate value="${firstDayOfMonth.time}" pattern="dd/MM/yyyy"/>
<fmt:formatDate value="${firstDayOfPreviousMonth.time}" pattern="dd/MM/yyyy"/>
<fmt:formatDate value="${firstDayOfNextMonth.time}" pattern="dd/MM/yyyy"/>
If you're not on EL 2.2 yet, then your best bet is preparing them in a servlet.
Upvotes: 1