Updated March 29, 2023
Definition on XML Date
XML Date is defined as a data type to specify the date in the XML Documents. According to W3C XML Schema, a date is a period of one day in its time zone. The date rule could be customized according to the requirements where sometimes it is necessary to do some date operations or parse dates to a specific format provided time zone should be specified if not local time is used. And the date format is defined by date pattern Strings by assigning letters from A to Z.
In this article, we have used a Class XML Gregorian Calendar for the data Utilities.
Syntax
The XML format for Date is given in the following formats
CCYY-MM-DD
The Formal Structure in Schema is given as:
<xsd : date>
Where the data type specifies Year, Month, and Day. It’s a finite-length sequence of characters with yy-mm-dd. The four-digit numeric represents a year, the negative value is restricted, and the year 0000 is neglected. And there is a symbol ‘- ‘separator between this format; finally, two-digit numerals signify month and date.
The element declaration is illustrated as
<xs: element name ="dob"; type = " xs:date"/>
The current date on Xpath is defined as
xs:date fn:current-date()
How does Date function work in XML?
Generally, this Date function includes Data types like
- xs:dateTime (CCYY-MM-DDThh:mm:ss)
- xs:date (CCYY-MM-DD)
- xs:time (hh:mm:ss)
- xs:gYearMonth (CCYY-MM)
- xs:gYear (CCYY)
- xs:gMonthDay (–MM-DD)
- xs:gMonth (–MM–)
- xs:gDay (—DD)
and XML formatter prefers to use Simple Date Format, and it is not thread-safe. Also, this constructor is not supported in all the local files. The format comes like this:
public SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols)
The Gregorian Calendar is specified as
<xsd:simpleType name="date" id="da">
<xsd:restriction base="xsd:anySimpleType">
<xsd:whiteSpace value="hello" fixed="true"/>
</xsd:restriction>
</xsd:simpleType>
The valid values of <xsd:date> is
2011-11-21
2011-11-21 +02:00
2011-11-21 Z
2011-11-21+00:00
2011-11-21
2011-02-03
The value of the datetime given is parsed by the XML parser, which converts the datetime value declared in the input XML to the value of the local time zone format. Thus, even a daylight-saving option could be made.
Using the Current date() function to display the current date of that day. This function is called without passing any parameters. As a result, it returns the date manipulated from the System time, i.e., gives out a constant value. Let’s see a simple working code of the XSD file.
<?xml version="1.0" encoding="utf-8"?>
<xsl: stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl: template match="/">
<html>
<body>
<h3>Display Date</h3>
The current date today is:
<xsl:value-of select="current-date ()" />
<br />
</body>
</html>
</xsl: template>
</xsl: stylesheet>
And in Xpath, we have like
<xf:output value="exf:format-datetime(currentdate,'d')" />
<xf:output value="exf:format-datetime(fn:current-date(),'D')" />
And Few functions on Date are dateTime (), year-from-dateTime (), year-from-date(date), month-from-date(date) , day-from-date(date).
Next, for the sample XML schema, the customization of XML date and time is specified as
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="divya Ro">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="dOB" type="xsd:date" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
And now, in the java file, the dob is a part of gregorgian Calendar
public class Client {
@XmlElement(name = "dob")
@XmlSchemaType(name = "date")
protected XMLGregorianCalendar dateOfBirth;
public XMLGregorianCalendar getDateOfBirth()
{return dateOfBirth;}
public void setDateOfBirth(XMLGregorianCalendar value)
{this.dateOfBirth = value;
}
}
Examples
Now let’s see how this function works well in XSLT and java.
Example#1 – Simple XML file displays the date
date.xml
<?xml version="1.0" encoding="UTF-8"?>
<Client>
<Dob>2020-03-11T11:14:15Z</Dob>
<Residence>
<Line1>38, Laciys Street</Line1>
<Line2>Flaytown, Switzerland</Line2>
</Residence>
</Client>
<Goods>
<Phone>0123-67542</Phone>
<Address>
<Line1>67, Washington Street/Line1>
<Line2>Zaeooper Mark Avenue</Line2>
</Address>
</goods>
Output:
Example#2
Educ.java
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class Educ
{
private final static String TIMESTAMP_PATTERN
= "MM/dd/yyyy hh:mm a z";
private final static DateTimeFormatter DATE_TIME_FORMATTER
= DateTimeFormatter.ofPattern(TIMESTAMP_PATTERN);
public static void main(String[] args)
throws DatatypeConfigurationException
{
GregorianCalendar c = new GregorianCalendar();
c.setTime(new Date());
XMLGregorianCalendar xc = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(c);
ZonedDateTime zon = xc.toGregorianCalendar().toZonedDateTime();
System.out.println( DATE_TIME_FORMATTER.format(zon) );
ZonedDateTime zond = zon.withZoneSameInstant(ZoneId.of("UTC"));
System.out.println( DATE_TIME_FORMATTER.format(zond) );
}
}
Explanation:
The above code snippets use Date Time Formatter to display a date. And when we execute, the output looks like>
Output:
Example#3 – Showing java code to convert Date Object to String Value Using Gregorian Calendar
Rule.java
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class Rule {
public static void main(String[] args) throws DatatypeConfigurationException
{
GregorianCalendar gca = new GregorianCalendar();
gca.setTime(new Date());
XMLGregorianCalendar xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar(gca);
System.out.println(convertXmlGregorianToString(xgc));
}
public static String convertXmlGregorianToString(XMLGregorianCalendar xgc)
{
DateFormat datef = new SimpleDateFormat("MM/dd/yyyy hh:mm a z");
GregorianCalendar gCalendar = xgc.toGregorianCalendar();
Date dd = gCalendar.getTime();
String dStr = datef.format(dd);
return dStr;
}
}
Explanation:
The above java code converts an XML file document into java code by converting their data objects to display date. It uses simple packages like Date Format and Simple Date Format.
Output:
Example#4 – Using a Style sheet to give out the date.
.xsl
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<html>
<body>
<table border="1">
<xsl:apply-templates select="TRSummary/TravellerRequest"/>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="RequestDate">
<td>
<xsl:value-of select="format-dateTime(.,'[M01]/[D01]/[Y0001]')" />
</td>
</xsl:template>
<xsl:template match="TravellerRequest">
<tr>
<xsl:apply-templates select="RequestDate"/>
</tr>
</xsl:template>
</xsl:stylesheet>
tester.xml
<?xml version="1.0"?>
<TRSummary>
<TravellerRequest>
<TravelRequestNumber>338</TravelRequestNumber>
<OriginatorName>SureshVL RonVL</OriginatorName>
<RequestDate>2020-01-09T17:51:01.67+05:30</RequestDate>
<CostCenter>800</CostCenter>
<ProjectManagerName>Prasannavl Athinavl Athinavl</ProjectManagerName>
<JobNumber>1524</JobNumber>
<ElementNumber>1454</ElementNumber>
<Remarks>remarks</Remarks>
<ExpectedTravelCost>1500</ExpectedTravelCost>
<PMC>Industry international</PMC>
</TravellerRequest>
<TravellerRequest>
<TravelRequestNumber>338</TravelRequestNumber>
<OriginatorName>SureshVL RonVL</OriginatorName>
<RequestDate>2020-01-09T17:51:01.67+05:30</RequestDate>
<CostCenter>800</CostCenter>
<ProjectManagerName>Prasannavl Athinavl Athinavl</ProjectManagerName>
<JobNumber>1234</JobNumber>
<ElementNumber>1234</ElementNumber>
<Remarks>remarks</Remarks>
<ExpectedTravelCost>1500</ExpectedTravelCost>
<PMC>Industry international</PMC>
</TravellerRequest>
</TRSummary>
Explanation:
Here we have used an XML file with various elements, and XSLT is created,
Output:
Example#5 – Xml date using C#
Code:
using System;
using System.IO;
using System.Xml;
public class test
{
public static void Main()
{
Int16 cid = 3252;
String oID = "3524f5";
DateTime orderDate = new DateTime();
orderDate = DateTime.Now;
Double price = 20.95;
XmlTextWriter writer = new XmlTextWriter (Console.Out);
writer.Formatting = Formatting.Indented;
writer.WriteStartElement("order");
writer.WriteAttributeString("date", XmlConvert.ToString(orderDate, "yyyy-MM-dd"));
writer.WriteAttributeString("time", XmlConvert.ToString(orderDate, "HH:mm:ss"));
writer.WriteElementString("orderID", oID);
writer.WriteElementString("custID", XmlConvert.ToString(cid));
writer.WriteElementString("price", XmlConvert.ToString(price));
writer.WriteEndElement();
writer.Close();
}
}
Explanation:
The above code automatically generates the current date from the System, which is shown below. The XML is written using the writer methods, where it starts from the root element ‘order.’
Output:
Conclusion
Therefore this article shows how to apply Date Format value types in java and also taught us the customization formats by changing the different settings as explained in the working sections.
Recommended Articles
This is a guide to XML Date. Here we discuss how the XML date function works well in XSLT and java, along with different examples and its code implementation. You may also have a look at the following articles to learn more –