11

I've seen some posts about date comparisons in JSTL, but I still can't get it to work.

I have a date field, which I want to test whether is after 01-01-1970.

<c:if test="${user.BirthDate > whatGoesHere}">
    <doSomeLogic/>
</c:if>

Maybe a bean should be used?

Thanks !

Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
Nati
  • 1,034
  • 5
  • 19
  • 46

5 Answers5

19

Just use <fmt:formatDate> to extract the year from it so that you can do the math on it.

<fmt:formatDate value="${user.birthDate}" pattern="yyyy" var="userBirthYear" />
<c:if test="${userBirthYear le 1970}">
    <doSomeLogic/>
</c:if>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 2
    Comparing the year of a Date is Avery limited use case. If you want to compare two Dates down to the millisecond, use built in Comparator of Date. Saurabh Ande answered it correctly below. This also doesn't answer the problem, it appears the OP needs it to at least day of month precision. – Michael Peterson Sep 13 '18 at 19:01
9

U can use jstl and usebean something like this

    <jsp:useBean id="now" class="java.util.Date"/>
    <c:if test="${someEvent.startDate lt now}"> 
    It's history!</c:if>
Hardik Gajjar
  • 1,024
  • 12
  • 27
Saurabh Ande
  • 427
  • 3
  • 13
6

You could also add a boolean getter to you bean:

public boolean isBirthDateAfter1970(){
    return birthDate.after(dateOf1970);
}

So you can use the following EL:

<c:if test="${user.birthDateAfter1970}">
   You were born after the sixties.
</c:if>
Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
3
<c:if test="${date1.time > date2.time}">...</c:if>

or lt,=,gt:

<c:if test="${date1.time gt date2.time}">...</c:if>

We exploit Long getTime() method of java.util.Date.

gavenkoa
  • 45,285
  • 19
  • 251
  • 303
0

You can use the (deprecated) methods getYear(), getMonth(), etc.

<c:if test="${user.BirthDate.year > 99}">
  <doSomeLogic/>
</c:if>

Note that getYear() returns the year number - 1900.

gvlasov
  • 18,638
  • 21
  • 74
  • 110
Dwight
  • 131
  • 1
  • 3