Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print current date in JSP?

Tags:

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() %> 
like image 858
sprugman Avatar asked Sep 10 '10 15:09

sprugman


People also ask

Which of the following code will take us to view show date JSP?

Show activity on this post. String df = new SimpleDateFormat("dd/MM/yy");

Which of the following is a valid method for date in JSP?

You can use the methods before( ), after( ), and equals( ) because the 12th of the month comes before the 18th; for example, new Date(99, 2, 12). before(new Date (99, 2, 18)) returns true. You can use the compareTo( ) method; this method is defined by the Comparable interface and implemented by Date.


2 Answers

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

like image 137
BalusC Avatar answered Oct 11 '22 19:10

BalusC


My solution:

<%@page import="java.util.Calendar"%> <%@page import="java.util.GregorianCalendar"%>     <%       GregorianCalendar cal = new GregorianCalendar();       out.print(cal.get(Calendar.YEAR));     %> 
like image 40
Benny Neugebauer Avatar answered Oct 11 '22 20:10

Benny Neugebauer