1

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

例如,如何以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来处理日期时间?(它没有像上面这样的边缘情况)

让这些函数使用“向正无穷大的一半”规则,其中一半是 30.0 秒。

4

2 回答 2

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
};
于 2018-11-15T13:44:00.050 回答
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) )
};

这个解决方案对于 casexs:timexs:dateTimetypes 是统一的。

于 2019-11-01T10:08:52.967 回答