mingo
Version:
MongoDB query language for in-memory objects
33 lines (32 loc) • 866 B
JavaScript
import { computeValue } from "../../../core";
import { computeDate, DURATION_IN_MILLIS } from "./_internal";
const $dateDiff = (obj, expr, options) => {
const args = computeValue(obj, expr, null, options);
const d1 = computeDate(obj, expr.startDate, options);
const d2 = computeDate(obj, expr.endDate, options);
let diff;
switch (args.unit) {
case "year":
case "quarter":
case "month":
diff = diffYQM(d1, d2, args.unit);
break;
default:
diff = (d2.getTime() - d1.getTime()) / DURATION_IN_MILLIS[args.unit];
}
return diff;
};
const unitMonths = {
year: 12,
quarter: 3,
month: 1
};
function diffYQM(d1, d2, unit) {
let months = (d2.getUTCFullYear() - d1.getUTCFullYear()) * 12;
months -= d1.getUTCMonth();
months += d2.getUTCMonth();
return Math.trunc(months / unitMonths[unit]);
}
export {
$dateDiff
};