XForms/Formatting a date

From Wikibooks, open books for an open world
< XForms
Jump to: navigation, search

Motivation[edit]

XML stores dates in the format YYYY-MM-DD such as 2007-08-30. Unfortunately this is usually not the way users want to view their dates.

This example XForms program uses CSS to hide an input date and an XPath expression to get the date to display in the MM/DD/YYYY format typically used in the US.

Screen Image[edit]

Date selector before calendar icon selected.
Date selector after calendar icon selected.

Link to XForm Example[edit]

Link to Date Format External Example

Sample Program[edit]

<html
  xmlns="http://www.w3.org/1999/xhtml" 
  xmlns:xf="http://www.w3.org/2002/xforms"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:ev="http://www.w3.org/2001/xml-events"
    xmlns:d="http://www.mydata.com/xmlns/data">
    <head>
        <title>Demo of date formatting using XPath concat and substring.</title>
        <style type="text/css"><![CDATA[
    @namespace xf url('http://www.w3.org/2002/xforms');
 
    .hidden .xf-value {
       display:none;
    }
]]>
      </style>
 
       <xf:model>
          <xf:instance xmlns="">
             <MyModel>
               <MyDate>2006-09-12</MyDate>
             </MyModel>
          </xf:instance>
          <xf:bind nodeset="/MyModel/MyDate" type="xs:date" />
       </xf:model>
   </head>
   <body>
        <xf:input class="hidden" ref="/MyModel/MyDate" incremental="true">
            <xf:label>Select Date: </xf:label>
        </xf:input>
        <!-- get the month (two characters wide starting at character number 6), then the day then the year -->
        <xf:output           
            value="concat(substring(/MyModel/MyDate,6,2),
            '/',
            substring(/MyModel/MyDate,9,2),
            '/',
            substring(/MyModel/MyDate,1,4))"
        />
    </body>
</html>

Discussion[edit]

The CSS style sheet hides the input field. The input has the class="hidden" attribute.

The output is formatted using the following XPath expression:

concat(
   substring(/MyModel/MyDate,6,2),
   '/',
   substring(/MyModel/MyDate,9,2),
   '/',
   substring(/MyModel/MyDate,1,4)
)

Concat is the XPath concatenation operator. The input is in the format: "YYYY-MM-DD". We just need to reach in and get the correct characters out.

  1. The first substring goes to the 6th characer and pulls out the two month (MM) characters.
  2. The second substring starts at the 9th character and gets two day (DD) characters.
  3. The last substring returns characters 1-4 which are the four year characters (YYYY).

You do not have to display all four letters in the year. By changing the last substring from:

substring(/MyModel/MyDate,1,4)

to be

substring(/MyModel/MyDate,3,4)

You will only get the last two digits of the year.


Next Page: Upload | Previous Page: Selecting a Date

Home: XForms