In JSP, you'd normally like to use JSTL <fmt:formatDate> for this. You can of course also throw in a scriptlet with SimpleDateFormat, but scriptlets are strongly discouraged since 2003.
Assuming that ${bean.date} returns java.util.Date, here's how you can use it:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
...
<fmt:formatDate value="${bean.date}" pattern="yyyy-MM-dd HH:mm:ss" />
If you're actually using a java.util.Calendar, then you can invoke its getTime() method to get a java.util.Date out of it that <fmt:formatDate> accepts:
<fmt:formatDate value="${bean.calendar.time}" pattern="yyyy-MM-dd HH:mm:ss" />
Or, if you're actually holding the date in a java.lang.String (this indicates a serious design mistake in the model; you should really fix your model to store dates as java.util.Date instead of as java.lang.String!), here's how you can convert from one date string format e.g. MM/dd/yyyy to another date string format e.g. yyyy-MM-dd with help of JSTL <fmt:parseDate>.
<fmt:parseDate pattern="MM/dd/yyyy" value="${bean.dateString}" var="parsedDate" />
<fmt:formatDate value="${parsedDate}" pattern="yyyy-MM-dd" />
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="UTF-8" />
<title>JSP with the current date</title>
</head>
<body>
<%java.text.DateFormat df = new java.text.SimpleDateFormat("dd/MM/yyyy"); %>
<h1>Current Date: <%= df.format(new java.util.Date()) %> </h1>
</body>
</html>
Output: Current Date: 10/03/2010
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With