Thody
Thody

Reputation: 1980

Present today's date as "Today" rather than "dd/mm/yyyy" in a JSP

Given a java.util.Date, what's the best way to display the date as Today rather than in some version of dd/mm/yyyy in a JSP?

Given a future date, I'd still like it to display in a dd/mm/yyyy format, but today should present as Today.

Upvotes: 2

Views: 3283

Answers (3)

Tym Pollack
Tym Pollack

Reputation: 125

You can compare the date in question to the current date (given by creating a new Date() instance. Does that help?

DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
Date someDate = df.parse("10/13/2011");

if (someDate.equals(df.parse(new Date())))
  displayDate = "Today";
else
  displayDate = someDate.toString();

EDIT: the following changes would make this work:

DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
if (someDate.equals(df.parse(df.format(new Date()))))

Upvotes: 0

BalusC
BalusC

Reputation: 1108642

The proper JSP/JSTL way would be using JSTL <fmt:formatDate>. You can use <jsp:useBean> to construct and put a java.util.Date in the page scope.

<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<jsp:useBean id="today" class="java.util.Date" />
<fmt:formatDate var="todayString" value="${today}" pattern="dd/MM/yyyy" />
...
<fmt:formatDate var="dateString" value="${bean.date}" pattern="dd/MM/yyyy" />
<p>The date is: ${todayString == dateString ? 'Today' : dateString}</p>

Note that I fixed mm to be MM. The mm stands for minutes, MM for months. See also SimpleDateFormat javadoc.

Upvotes: 3

James Jithin
James Jithin

Reputation: 10565

This will do:

<%
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date currentDate  = java.util.Calendar.getInstance().getTime();
Date myDate = someDate;
%>
<%=sdf.format(currentDate).equals(sdf.format(myDate))?"Today":sdf.format(myDate)%>

Upvotes: 3

Related Questions