XML-XSLT:如何比较字符串中的两个日期 [英] XML-XSLT : How to compare two dates which are in String
问题描述
我知道这个问题可能会重复,我也浏览过类似的文章和问题,但我还没有找到确切的解决方案.
I know this question might get repeated and also I have went through similar articles and question but I have not found the exact solution.
现在的问题我正在使用 XSLT 或 XPATH 来转换 xml.在 XML 中,有两个字符串变量.一个是 OldDate
,第二个是 CurrentDate
.
Now the question
I am using XSLT or XPATH to transform the xml. Here in XML two string variables are there. one is OldDate
and second is CurrentDate
.
Ex : $oldDate = '29.05.2015 15:25:06'
$currentDate ='27.07.2015 14:28:02'.
现在我想比较这两个日期.
Now I want to compare those two dates.
If $oldDate > $currentDate then 'OK' else 'Not Ok'.
由于我是使用 XSLT 和 XPATH 的新手,所以我不知道如何从其他文章中给出的答案开始.
As I am new to use XSLT and XPATH I did not get that how to proceed from the given answers in other articles.
为此提供一个完美的解决方案会很棒.
It will be great-full to provide a perfect solution for this.
谢谢.
推荐答案
XSLT (2.0) 仅识别 YYYY-MM-DD
格式的日期,以及 YYYY-MM 格式的日期时间-DDThh:mm:ss
格式.为了将字符串作为日期,(或者,在这种情况下,日期时间)进行比较,您必须首先将它们转换为有效的日期时间.由于您需要多次执行此操作,因此为此目的构造一个函数会很方便:
XSLT (2.0) recognizes dates in YYYY-MM-DD
format only, and date-times in YYYY-MM-DDThh:mm:ss
format only. In order to compare the strings as dates, (or, in this case, date-times), you must first convert them to valid date-times. Since you need to do this more than once, it would be convenient to construct a function for this purpose:
XSLT 2.0
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:my="http://www.example.com/my"
exclude-result-prefixes="xs my">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="oldDate" select="'29.05.2015 15:25:06'" />
<xsl:variable name="currentDate" select="'27.07.2015 14:28:02'" />
<xsl:function name="my:string-to-datetime">
<xsl:param name="string"/>
<xsl:variable name="parts" select="tokenize($string,'\.|\s')"/>
<xsl:sequence select="xs:dateTime(concat($parts[3], '-', $parts[2], '-', $parts[1], 'T', $parts[4]))" />
</xsl:function>
<xsl:template match="/">
<result>
<xsl:value-of select="if (my:string-to-datetime($oldDate) gt my:string-to-datetime($currentDate)) then 'OK' else 'Not Ok'" />
</result>
</xsl:template>
</xsl:stylesheet>
结果
<?xml version="1.0" encoding="utf-8"?>
<result>OK</result>
请注意,这里假设您的字符串采用 DD.MM.YYYY hh:mm:ss
格式 - 即天数填充为两位数 - 否则还有更多工作要做.
Note that this assumes your strings come in a DD.MM.YYYY hh:mm:ss
format - i.e. that the days are padded to two digits - otherwise there's more work to be done.
这篇关于XML-XSLT:如何比较字符串中的两个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!