sprugman
sprugman

Reputation: 19831

How to print current date in JSP?

I want to do something like this:

 <?php echo date('Y'); ?>

But then in a .jsp file. All the tutorials I'm seeing require building a class somewhere. We're running appFuse and Tapestry. Surely one of those (if not Java itself) provide us with something to do this sort of thing without all that overhead.

This seems like it should work, but doesn't:

 <%= new Date.getYear() %>

Upvotes: 24

Views: 46213

Answers (6)

Brice Roncace
Brice Roncace

Reputation: 10650

<%@page import="java.time.LocalDate"%>

${LocalDate.now().year}

Upvotes: 0

Kamil
Kamil

Reputation: 424

In Java 8 to print year you can use:

<%= LocalDate.now().getYear() %>

Upvotes: 1

jtn
jtn

Reputation: 41

<%= new java.util.Date().getYear() + 1900 %>

Upvotes: 3

Benny Code
Benny Code

Reputation: 54802

My solution:

<%@page import="java.util.Calendar"%>
<%@page import="java.util.GregorianCalendar"%>
    <%
      GregorianCalendar cal = new GregorianCalendar();
      out.print(cal.get(Calendar.YEAR));
    %>

Upvotes: 2

duffymo
duffymo

Reputation: 308743

You should be writing JSPs using JSTL and using its <fmt> tags to format dates and such.

Upvotes: -2

BalusC
BalusC

Reputation: 1108642

Use jsp:useBean to construct a java.util.Date instance and use JSTL fmt:formatDate to format it into a human readable string using a SimpleDateFormat pattern.

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<jsp:useBean id="date" class="java.util.Date" />
Current year is: <fmt:formatDate value="${date}" pattern="yyyy" />

The old fashioned scriptlet way would be:

<%= new java.text.SimpleDateFormat("yyyy").format(new java.util.Date()) %>

Note that you need to specify the full qualified class name when you don't use @page import directives, that was likely the cause of your problem. Using scriptlets is however highly discouraged since a decade.

This all is demonstrated in the [jsp] tag info page as well :)

Upvotes: 70

Related Questions