CosmosDB 存储过程及其对 new Date()
的处理和日期比较的指导有限。
以下代码是一个 CosmosDB 存储过程,用于在给定时间后“卡住”文档的写入。属性 currentDoc.FreezeDate
采用 ISO-8601 格式,例如'2017-11-15T13:34:04Z'。
注意:这是我试图了解的情况的示例。它不是生产代码。
function tryUpdate(newDoc) {
__.queryDocuments(
__.getSelfLink(),
{ /* query to fetch the document */ },
(error, results) => {
var currentDoc = results[0]; // doc from the database
// fail if the document is still locked
if (new Date(currentDoc.FreezeDate) < new Date()) {
getContext().getResponse().setBody({ success: false });
return;
}
// else update the document
/* snip */
}
);
}
我的问题是:在 CosmosDB 存储过程中,new Date()
是否受时区影响,特别是考虑到数据库可能与调用代码位于不同的区域?这里的日期比较代码是否在所有情况下都有效?
最佳答案
据我所知,CosmosDB 存储的 DateTime 值没有相应的时区,也就是。不是 DateTimeOffset。这意味着代码在何处执行无关紧要,因为它总是被规范化为如下所示:
"2014-09-15T23:14:25.7251173Z"
Javascript Date object are timestamps - they merely contain a number of milliseconds since the epoch. There is no timezone info in a Date object. Which calendar date (day, minutes, seconds) this timestamp represents is a matter of the interpretation (one of to...String methods).
(取自Parse date without timezone javascript)
换句话说,无论您在世界的哪个地方,new Date()
的内部值始终相同。
如果您想消除不确定性以换取可读性,我建议只存储自纪元(Unix 时间)以来的秒数或毫秒数。这也是日期内部使用的内容(new Date().value
- 毫秒)。顺带一提,内部cosmos文档字段_ts
也是一个epoch格式的时间戳。
请注意,new Date()
的值可能会偏离“正确的全局时间”几分钟——我不知道 Azure/Cosmos 是否保证一定的偏差窗口。
关于javascript - 在 Cosmos DB 存储过程中创建和比较日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47309307/