开发者

How to get the time from a dateTime value?

I have a XML attributes, <EventDate>2011-06-16 08:00:00</EventDate> and I want to extract 08:00:00 using XSLT.

I saw there was fn:hours-from-dateTime(datetime) thanks to w3schools. So I'm wondering, why is there no fn:time-from-dateTime(datetime)?

And how do I use it? My current code is :

<td><xsl:value-o开发者_StackOverflow社区f select="@EventDate"/></td>

Which display the dateTime correctly. However :

 <td><xsl:value-of select="hours-from-dateTime(@EventDate)"/></td>

Doesn't work.

Finally, is there something more elegant than doing :

<td><xsl:value-of select="hours-from-dateTime(@EventDate)"/>:
<xsl:value-of select="minutes-from-dateTime(@EventDate)"/>:
<xsl:value-of select="seconds-from-dateTime(@EventDate)"/></td>

?


Just use a cast or constructor function:

<xsl:value-of select="xs:time(@dateTime)"/>

This assumes that attribute @dateTime is of type xs:dateTime as a result of schema processing. If you're not running a schema-aware processor, you'll need to cast it to xs:dateTime first:

<xsl:value-of select="xs:time(xs:dateTime((@dateTime))"/>

and of course that space between the date and time needs to be a "T" for this to work.


Thanks for both suggestion, but since I didn't really need it as a dateTime variable, I just treated it as a string and used :

<xsl:value-of select="substring-after(@EventDate, ' ')"/>


The date you're starting with is missing the time separator 'T' so you'll need to insert that if you want to use the dateTime functions.

I suggest the following:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs fn" version="2.0"
   xmlns:fn="http://www.w3.org/2005/xpath-functions">
   <xsl:template match="/">
    <foo>
        <xsl:variable name="time" select="translate(string(/input), ' ', 'T')"/>
        <xsl:value-of select="fn:format-dateTime(xs:dateTime($time), '[h]:[m01]:[s01]')"/>        
    </foo>
</xsl:template>

This assumes an input as follows:

<input>2011-06-16 09:00:00</input>

For further reference, see the format-dateTime function in the xslt20 spec. There are many different options for formatting the date time value using the "picture string" argument.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜