跳轉到內容

XForms/日期格式化

來自華夏公益教科書,開放的書籍,開放的世界

XML 以 YYYY-MM-DD 格式儲存日期,例如 2007-08-30。不幸的是,這通常不是使用者希望檢視日期的方式。

此示例 XForms 程式使用 CSS 隱藏輸入日期,並使用 XPath 表示式獲取日期以美國常用的 MM/DD/YYYY 格式顯示。

螢幕影像

[編輯 | 編輯原始碼]
選擇日曆圖示之前的日期選擇器。
選擇日曆圖示之後的日期選擇器。
[編輯 | 編輯原始碼]

連結到日期格式外部示例

示例程式

[編輯 | 編輯原始碼]
<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>

CSS 樣式表隱藏了輸入欄位。輸入具有 class="hidden" 屬性。

輸出使用以下 XPath 表示式格式化

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

Concat 是 XPath 連線運算子。輸入格式為:"YYYY-MM-DD"。我們只需要找到並獲取正確的字元。

  1. 第一個子字串到第 6 個字元,並提取兩個月份 (MM) 字元。
  2. 第二個子字串從第 9 個字元開始,獲取兩個日期 (DD) 字元。
  3. 最後一個子字串返回第 1-4 個字元,它們是四個年份字元 (YYYY)。

您不必顯示年份中的所有四個字母。透過將最後一個子字串從

substring(/MyModel/MyDate,1,4)

更改為

substring(/MyModel/MyDate,3,4)

您將只獲得年份的後兩位數字。


下一頁: 上傳 | 上一頁: 選擇日期
主頁: XForms
華夏公益教科書