24

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() %>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
sprugman
  • 19,351
  • 35
  • 110
  • 163
  • There seems to be some confusion of ideas here. You're either using Tapestry or you're using JSPs, but hardly both, or are you? – Henning Sep 10 '10 at 15:45
  • Well, given that I don't know what I'm doing :), yes, I'm editing both .jsp and .tml files, depending. The rough page frame is mostly jsps so far, e.g. default.jsp, header.jsp, footer.jsp. I'm assuming the page content will be more .tml. (The framework was set-up for me by someone else.) – sprugman Sep 10 '10 at 19:30
  • Interesting mixture. Good luck :) – Henning Sep 11 '10 at 10:04
  • heh. thanks. yeah, know which files to touch, and which to leave alone, and what goes where is always the hardest part about learning these things... :) – sprugman Sep 12 '10 at 20:15

6 Answers6

70

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 :)

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
3

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

jtn
  • 41
  • 1
2

My solution:

<%@page import="java.util.Calendar"%>
<%@page import="java.util.GregorianCalendar"%>
    <%
      GregorianCalendar cal = new GregorianCalendar();
      out.print(cal.get(Calendar.YEAR));
    %>
Benny Code
  • 51,456
  • 28
  • 233
  • 198
1

In Java 8 to print year you can use:

<%= LocalDate.now().getYear() %>
Kamil
  • 424
  • 4
  • 8
0
<%@page import="java.time.LocalDate"%>

${LocalDate.now().year}
Brice Roncace
  • 10,110
  • 9
  • 60
  • 69
-2

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

duffymo
  • 305,152
  • 44
  • 369
  • 561