You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MarkLogic中计算两个xs.date类型的天数差值?

Get Numeric Day Difference Between Two xs.date Values

Hey there! Let's work through this to get you the numeric day count you need. The issue you're hitting is that while your current approach uses a duration-related function, there's a more direct way to get a numeric result, plus we can fix up the existing method if needed.

First, let's restate your setup code for clarity:

var date1 = xs.date("2018-03-29"); 
var date2 = xs.date("2018-04-15");

Why Your Current Try Isn't Returning a Numeric Value

When you subtract two xs.date values (date2 - date1), you end up with an xs:dayTimeDuration object. If fn.daysFromDuration is returning a duration instead of a number, it might be due to a syntax mismatch (like using camelCase instead of the standard kebab-case fn:days-from-duration) or environment-specific behavior. But even if that worked, there's a cleaner solution.

The Best Function: fn:days-between

The fn:days-between function (available in XQuery 3.1+ and supported in tools like Saxon JS) is made exactly for this. It takes two xs.date parameters and returns an xs:integer—a pure numeric value—representing the days between the dates.

Here's how to use it:

var dayDifference = fn.daysBetween(date1, date2);

For your example dates (2018-03-29 to 2018-04-15), this will return 17 (since March has 31 days: 31-29 + 15 = 17)—exactly the numeric result you're after.

If fn:days-between Isn't Available

If you're stuck in an environment that doesn't support fn:days-between, you can still use the duration approach correctly. Just ensure you're using the proper function syntax to extract the integer day count from the duration:

var durationDiff = date2 - date1;
var dayDifference = fn.daysFromDuration(durationDiff);
// Or use standard XQuery syntax: fn:days-from-duration($durationDiff)

This should pull the integer day count from the duration object. If it's still returning a duration, double-check your environment's docs to confirm the correct function name and return type.


内容的提问来源于stack exchange,提问作者Ryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:24:54