XForms/日期格式化
外觀
< 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"。我們只需要找到並獲取正確的字元。
- 第一個子字串到第 6 個字元,並提取兩個月份 (MM) 字元。
- 第二個子字串從第 9 個字元開始,獲取兩個日期 (DD) 字元。
- 最後一個子字串返回第 1-4 個字元,它們是四個年份字元 (YYYY)。
您不必顯示年份中的所有四個字母。透過將最後一個子字串從
substring(/MyModel/MyDate,1,4)
更改為
substring(/MyModel/MyDate,3,4)
您將只獲得年份的後兩位數字。