Date in Castor

V

veerleverbr

Hi,

I have an XML file with dates in it, formatted as:
<birthday>
<day>21>/day>
<month>06</month>
<year>1975</year>
</birthday>

I have an xsd that describes this as:
<xs:complexType name="dateDef">
<xs:sequence>
<xs:element name="day" type="xs:integer" minOccurs="1"
maxOccurs="1"/>
<xs:element name="month" type="xs:integer" minOccurs="1"
maxOccurs="1"/>
<xs:element name="year" type="xs:integer" minOccurs="1"
maxOccurs="1"/>
</xs:sequence>
</xs:complexType>

When running SourceGenerator, Castor creates a class DateDef.java.

What do I have to change to make Castor understand that this is
actually a date, and that he has to turn it into the type
java.util.Date and that he has to validate wether this a valid date?

Any help would be appreciated...
Veerle
 
C

Chris

Dates in castor are a little bit tricky. I'm not quite sure but I think
castor itself saves the values in some kind of string format yyyy-mm-dd

So I recommend to format your date as a string in xsd-file.
<xsd:element name="AccessDate" type="xsd:string"/>


If you read the string date values use this method:

public static void setAccessDate(String selValue) {
Date calcDate;

try {
//Set input format of string date
java.text.SimpleDateFormat sdfInput = new
java.text.SimpleDateFormat(
"yyyy-MM-dd");

//Convert date in string format to date format
calcDate = sdfInput.parse(selValue);
}
catch (Exception e) {
//Set date on today
calcDate = (new Date());
}
}

//Set value of input field
datefieldAccessDate.setValue(calcDate);
}


If you write back to castor, first convert date values in your application
to string values in this format. You could use the following function for
this task.

public static String getAccessDate() {
//Convert date to string in format yyyy-MM-dd
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
"yyyy-MM-dd");
String convertedDate = sdf.format(datefieldAccessDate.getValue());

//Return the converted date
return convertedDate;
}

Regards,
Chris
 
V

veerleverbr

No, I found a much better solution:

In the xsd is specify my date elements as: <xsd:element name="..."
type="xs:dateTime"/>

When I then generate my Castor objects, Castor automatically takes
java.util.Date as the type for these variables.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,589
Members
45,100
Latest member
MelodeeFaj
Top