You can create a user defined function. I created this directly in the explorer:
function AddMonths(dateTime, months) {
var date = new Date(dateTime);
var day = date.getUTCDate();
date.setUTCMonth(date.getUTCMonth() + months, 1);
var month = date.getUTCMonth();
date.setUTCDate(day);
if (date.getUTCMonth() !== month)
date.setUTCDate(0);
return date.toISOString();
}
The UDF is identified by ID (which doesn't have to match the function name in JavaScript). In this case I named it AddMonths
.
The UDF can the be used in queries:
SELECT * FROM c WHERE c.userid = '100' and c.Date > udf.AddMonths(c.preDate, -4)
Notice that offsetting a date by months is non-trivial because you have to take into account that months can have 28-31 days. I took inspiration from aMarCruz' answer here on Stack Overflow but you may have to consider if that is the right way for you to handle this.
If your dates were stored as UNIX timestamps (e.g. numbers) you could perform arithmetic directly in Cosmos SQL but to decide how many seconds to subtract for 4 months would still require a UDF so it's not really a better option.
One thing I noticed is that when storing C# DateTime
values in Cosmos they are specified with 100 nanosecond precision. However, in JavaScript (using toISOString
) the precision is 1 microsecond. This could potentially lead to confusing errors in certain corner cases so just be aware of this.