EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials XML Tutorial XML Date
Secondary Sidebar
XML Tutorial
  • Basic
    • What is XML?
    • XML Tags
    • XML URL
    • XPath Sibling
    • XML root element
    • XML Encryption
    • XML Parsing php
    • xml parsing with java
    • Dataset XML
    • XML Parser in C#
    • XML Tree
    • XML boolean
    • XML sitemap
    • XML Array
    • XML reserved characters
    • XML Viewer
    • XML Uses
    • XML Special Characters
    • XML generator
    • XML file format
    • XML DOM
    • XML ampersand
    • XML Mapping
    • XML File
    • XML Element
    • XML HttpRequest
    • XML XSD
    • XML Schema
    • XML Namespaces
    • XML Comments
    • XML Attributes
    • XML Encoding
    • XML Validation
    • XML CDATA
    • XML Database
    • XML Technologies
    • XML Error
    • XML DTD
    • XML Date
    • XML Parsers
    • String in XML
    • XML with CSS
    • XML Versions
    • XML Features
    • XML Commands
    • Servlet web.xml
    • XPath Injection
    • XPath Functions
    • XPath starts-with
    • XPath Selector
    • XPath Count
    • XPath XML
    • XML Parsing in Oracle
    • XML parsing in python
  • Xpath
    • What is XPath?
    • XPath namespace
    • XPath for JSON
    • XPath Last Element
    • Xpath Substring
    • XPath First Element
    • XPath local-name
    • XPath Multiple Attributes
    • XPath Matches
    • XPath Position
    • XPath Index
    • XPath regex
    • XPath id contains
    • XPath innertext
    • XPath Multiple Conditions
    • XPath Helper
    • XPath Generator
    • XPath ID
    • XPath Locator

XML Date

XML Date

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.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,883 ratings)

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:

XML Date Example 1

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:

XML Date Example 2

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:

XML Date Example 3

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:

Using Style sheet Example 4

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:

Using C# Example 5

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 –

  1. What is XML?
  2. XML Commands
  3. XML Features
  4. XML Interview Questions
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more