Struts 2 date tag formats the date string in two ways, one is by converting to the required format and second is by using the “nice” attribute and converting to the human readable format. This tutorials shows how to use the s:date tag for converting to the different formats for the same input.
1. Action Class
In the action class, initialize the date object with default values.
package javabeat.net.struts2; import java.util.Calendar; import java.util.Date; public class Struts2HelloWorldAction { private Date currentDate; public Date getCurrentDate() { return currentDate; } public void setCurrentDate(Date currentDate) { this.currentDate = currentDate; } this.userName = userName; } public String execute(){ Calendar cal = Calendar.getInstance(); cal.set(2013, 11, 13); Date newDate = cal.getTime(); setCurrentDate(newDate); return "success"; } }
2. Date Tag Example
Here it shows the three different variations of the output.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Struts 2 Date Tag Example </title> </head> <body> Default date format : <s:date name="currentDate" /><br> Date format in "dd/MM/yyyy" : <s:date name="currentDate" format="dd/MM/yyyy" /><br> Use Nice Attribute : <s:date name="currentDate" nice="true" /> </body> </html>
3. Struts.xml
<?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="tags" extends="struts-default"> <action name="datetag" class="javabeat.net.struts2.Struts2HelloWorldAction" method="execute"> <result name="success">/DateTag.jsp</result> </action> </package> </struts>
4. Date Tag Demo
If you access the application in the url http://localhost:80/Struts2App/datetag, you would see the following output.