Struts 2 “date” tag is used to format Date object in two ways :

  1. Custom date format (eg. “dd/MM/yyyy”).
  2. “nice” attribute to format date into an easy readable notations like “this date is 162 days ago”.

In this tutorial, it shows the use of Struts 2 “date” tag to format a Date object into “custom date format” and “easy readable notations“.

1. Action

An Action class to forward the request, and initialize a Date object with a predefined date.

DateTagAction.java

package com.mkyong.common.action;
 
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
 
import com.opensymphony.xwork2.ActionSupport;
 
public class DateTagAction extends ActionSupport{
 
	public Date customDate;
 
	public String execute() {
 
		Calendar cal = Calendar.getInstance();
		//set date to january 31, 2010
		cal.set(2010, 0, 31);
		Date newDate = cal.getTime();
 
		setCustomDate(newDate);
 
		return SUCCESS;
 
	}
 
	public Date getCustomDate() {
		return customDate;
	}
 
	public void setCustomDate(Date customDate) {
		this.customDate = customDate;
	}
 
}

2. date tag example

A JSP page to show the use of “date” tag to format a Date object in :

  1. Default date format.
  2. Custom date format.
  3. Easy readable notation.

date.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
 <html>
<head>
</head>
 
<body>
<h1>Struts 2 date tag example</h1>
 
<ol>
 
<li>
Default date format
--> <strong><s:date name="customDate" /></strong>
</li>
 
<li>
Date format in "dd/MM/yyyy"
--> <strong><s:date name="customDate" format="dd/MM/yyyy" /></strong>
</li>
 
<li>
In Date tag, set the nice attribute to "true"
--> <strong><s:date name="customDate" nice="true" /></strong>
</li>
 
</ol>
 
</body>
</html>

3. struts.xml

Link it ~

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
 	<constant name="struts.devMode" value="true" />
	<package name="default" namespace="/" extends="struts-default">
 
		<action name="dateTagAction" 
			class="com.mkyong.common.action.DateTagAction" >
			<result name="success">pages/date.jsp</result>
		</action>
 
	</package>
</struts>

4. Demo

http://localhost:8080/Struts2Example/dateTagAction.action

Output

Struts 2 date tag example

Reference

  1. Struts 2 date tag documentation
Tags :
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to the charity, thanks.

Related Posts

Popular Posts