Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a java Date to a ReadableInstant for Joda Time inside a JSP?

I instantiated a java.util.Date object called myDate in my controller and passed it to my JSP where I have a Joda Time JSP tag configured with this at the top of the page:

<%@taglib prefix="joda" uri="http://www.joda.org/joda/time/tags" %>

and of course the necessary Maven dependencies added to the project via the POM file.

However, when I try to access myDate from the JSP like this:

<joda:format value="${myDate}" style="SM" />

I get this error:

javax.servlet.jsp.JspException: 
value attribute of format tag must be a 
ReadableInstant or ReadablePartial, was: java.util.Date

Referring to the documentation for the Joda Time JSP tags, I can't tell how I should 'convert' my myDate to a ReadableInstant or ReadablePartial in the context of this JSP?

like image 986
Sam Bricket Avatar asked Feb 28 '11 02:02

Sam Bricket


People also ask

Is Joda-Time followed in Java 8?

Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java. util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java.

How do you create a date and time object in Java?

You can create a Date object using the Date() constructor of java. util. Date constructor as shown in the following example. The object created using this constructor represents the current time.

What is Joda-Time format?

Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat. Low level - builder.


1 Answers

The error message is self-explaining. The JodaTime tags doesn't accept a Java SE standard Date instance, but a JodaTime DateTime instance or whatever implements JodaTime's ReadableInstant or ReadablePartial.

You need to convert it before providing it to the view.

DateTime dateTime = new DateTime(date.getTime());
request.setAttribute("myDate", dateTime);
like image 80
BalusC Avatar answered Sep 29 '22 10:09

BalusC