季度日期计算[XQuery]



我正在尝试生成一个获取季度报告的报告,即基于startDate和endDate。如果XQuery或Marklogic中的季度名称为Q1,年份为参数,如何计算任何季度的startDate和endDate。

示例:如果我将季度=q1和年份=2018作为参数,那么我需要将startDate设置为2018年1月1日,将endDate设置为2017年3月31日

您可以使用functx:last-day-of-month()和其他标准日期函数来构造给定年份和季度的开始和结束日期。

下面的示例代码将返回一系列xs:date对象,第一个是开始日期,第二个是结束日期。

xquery version "1.0-ml";
import module namespace functx = "http://www.functx.com" 
at "/MarkLogic/functx/functx-1.0-doc-2007-01.xqy";
declare function local:quarter-range($year as xs:integer, $quarter as xs:integer) {
let $month := 3 * $quarter
let $end :=  xs:date($year || "-"|| substring(string(100 + $month), 2)||"-01")
let $start-date := $end - xs:yearMonthDuration("P2M")
let $end-date := functx:last-day-of-month($end)
return
($start-date, $end-date)
};
local:quarter-range(2018, 2)

您可以增强它,转而使用cts:element-range-query:构建并返回cts:and-query()

xquery version "1.0-ml";
import module namespace functx = "http://www.functx.com" 
at "/MarkLogic/functx/functx-1.0-doc-2007-01.xqy";
declare function local:quarter-range(
$element as xs:QName, 
$year as xs:integer, 
$quarter as xs:integer) 
as cts:query 
{
let $month := 3 * $quarter
let $end :=  xs:date($year || "-"|| substring(string(100 + $month), 2)||"-01")
let $start-date := $end - xs:yearMonthDuration("P2M")
let $end-date := functx:last-day-of-month($end)
return
cts:and-query((
cts:element-range-query($element, ">=", $start-date), 
cts:element-range-query($element, "<=", $end-date)
))
};
local:quarter-range(xs:QName("myDateElement"), 2018, 2)

最新更新