Ryan Cox
Ryan Cox

Reputation: 1

How to format sql date (yyyy-mm-dd) to display as just (yyyy) in jsp?

I have an sql entry of a date of birth (dob) that was pulled from query.jsp with jdbc, stored as dob, and sent to results.jsp. The sql date is in a yyyy-mm-dd format, but I need to display only the year. My current code for this issue:


<%@ page import="java.text.*" %>

<%
String birthdate = request.getParameter("dob");
SimpleDateFormat yearOnly = new SimpleDateFormat("yyyy");
Date year = yearOnly.parse(birthdate);
%>

ERROR Type mismatch: cannot convert from java.util.Date to java.sql.Date

How can I format my sql date to display only the year portion of the dob? Should I format in the query.jsp or the results.jsp?

Upvotes: 0

Views: 488

Answers (1)

Alan Hay
Alan Hay

Reputation: 23236

Avoid scriptlets in your JSP.

Convert the java.sql.Date to a java.util.Date:

java.util.Date newDate = new Date(rs.getDate("MY_COLUMN").getTime());

Declare a reference to the JSP formatting library at the top of your JSP:

<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>

and use the formatDate tag to output your date:

<fmt:formatDate pattern = "yyyy" value = "${dob}" /></p>

where dob is your request scoped attribute referenced via JSP EL.

https://www.tutorialspoint.com/jsp/jstl_format_formatdate_tag.htm

Upvotes: 0

Related Questions