Xpath中的回合时间

时间:2018-11-15 12:57:00

标签: datetime xpath xquery xpath-3.0

在XPath中舍入时间和dateTime的最简单正确的方法是什么?

例如,如何使用以下测试用例定义函数local:round-time-to-minutes

let $t1 := xs:time( "12:58:37" )
let $t2 := local:round-time-to-minutes( $t1 )
return format-time( $t2, '[H01]:[m01]:[s01]' )

将返回"12:59:00"。 不确定在“ 23:59:31”的情况下哪个更好—返回“ 00:00:00”或引发动态错误。

还有类似的函数local:round-datetime-to-minutes处理dateTime吗? (它没有上述这种极端情况)

让这些函数使用“朝正无穷大舍入一半”规则,其中一半为30.0秒。

2 个答案:

答案 0 :(得分:2)

这是@ michael.hor257k提出的解决方案在XQuery中的外观:

declare variable $ONE_MIN := xs:dayTimeDuration("PT1M");
declare variable $MIDNIGHT := xs:time("00:00:00");

declare function local:round-time-to-minutes($time) {
  $MIDNIGHT + round(($time - $MIDNIGHT) div $ONE_MIN) * $ONE_MIN
};

答案 1 :(得分:0)

另一种解决方案是从给定的dateTime中减去秒数,如果秒数不少于30,则增加一分钟(60秒)。

要将秒数转换为持续时间,我们将其乘以1S持续时间(实际上,编译器可以消除此操作)。

declare function local:round-time-to-minutes ( $time as xs:time ) {
  let $s := seconds-from-time( $time )
  return $time - xs:dayTimeDuration('PT1S') * ( $s - 60 * ($s idiv 30) )
};

declare function local:round-dateTime-to-minutes ( $dt as xs:dateTime ) {
  let $s := seconds-from-dateTime( $dt )
  return $dt - xs:dayTimeDuration('PT1S') * ( $s - 60 * ($s idiv 30) )
};

对于xs:timexs:dateTime类型的情况,此解决方案是统一的。