Hasif Subair
Hasif Subair

Reputation: 436

How to convert a calendar object to date in struts2 textfield tag

I am editing a users profile, I need a way to edit the user's date of birth. In my action class the dateOfBirth is a Calendar object. Now how can populate the date in the date of birth text field.

<s:textfield id="txtDob" name="dateOfBirth" />


public class Person {

    private Calendar dateOfBirth;
    public Calendar getDateOfBirth() {    
        return dateOfBirth;
    }
    public void setDateOfBirth(Calendar dateOfBirth) {    
        this.dateOfBirth = dateOfBirth;
    }
}

when i run the jsp, this is what i get inside the textfield

java.util.GregorianCalendar[time=366229800000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=1981,MONTH=7,WEEK_OF_YEAR=33,WEEK_OF_MONTH=3,DAY_OF_MONTH=10,DAY_OF_YEAR=222,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=2,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=19800000,DST_OFFSET=0]

Upvotes: 1

Views: 2305

Answers (2)

Ali Arslan
Ali Arslan

Reputation: 1047

Instead of using s:textfield tag try using dojo ajax sx:datetimepicker tag. Before using dojo tags add respective jars.

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>
<html>
<head>
<title>Example/title>
<s:head />
<sx:head />
</head>
<body>
<sx:datetimepicker name="dateOfBirth" label="Date Of Birth"
     displayFormat="MM/dd/yyyy" />
</body>
</html>

Upvotes: 2

Umesh Awasthi
Umesh Awasthi

Reputation: 23587

This is because struts2 has a set of type convertors out of the box and struts2 only supports date conversion and it uses the SHORT format for the Locale associated with the current request.

You can create your custom type convertor and can tell struts2 to use that type convertor for Calendar object. creating a custom type convertor is quite easy and straight forward.make use of StrutsTypeConverter class being provided by S2 for this purpose

 public class MyConverter extends StrutsTypeConverter {
    public Object convertFromString(Map context, String[] values, Class toClass) {
       .....
    }

    public String convertToString(Map context, Object o) {
       .....
    }
 }

Upvotes: 1

Related Questions