![](/img/trans.png)
[英]Converting ISO-8601 string to local date in typescript/javascript
[英]Getting ISO-8601 formatted date using Javascript in a Cosmos DB stored procedure
我正在为 Cosmos DB 编写一个存储过程。 我对 JavaScript 不是很熟悉。
我一直在尝试获取 ISO-8601 格式的Date
,但到目前为止没有成功。 根据我发现的一些文档,我应该能够在Date
上调用toISOString
。 这不起作用(“对象不支持属性或方法”错误)。
所以我找到了这个建议来自己定义原型:
function storedProcedure(arg) {
if (!Date.prototype.toISOString) {
// Here we rely on JSON serialization for dates because it matches
// the ISO standard. However, we check if JSON serializer is present
// on a page and define our own .toJSON method only if necessary
if (!Date.prototype.toJSON) {
var toISOString = function (date) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return date.getUTCFullYear() + '-' +
f(date.getUTCMonth() + 1) + '-' +
f(date.getUTCDate()) + 'T' +
f(date.getUTCHours()) + ':' +
f(date.getUTCMinutes()) + ':' +
f(date.getUTCSeconds()) + 'Z';
};
}
Date.prototype.toISOString = Date.prototype.toJSON;
}
var now = Date.now();
var iso8601 = now.toISOString();
console.log("ISO " + iso8601);
// other code
}
但是,这仍然失败:
Object doesn't support property or method 'toISOString'
我尝试完全删除原型,只使用一个带Date
的函数。 但是,随后发生了同样的错误,但对于其他成员,例如getUTCFullYear
。
我也尝试调用getSeconds
并且由于同样的原因失败了。 出于绝望,我尝试在这个答案中使用getKeys
函数列出对象的属性,它给了我一个空列表。
这里发生了什么? 我怎样才能获得一个 ISO-8601 格式的Date
表示 UTC 中的当前时间?
好吧,这似乎是因为我根据这些文档使用了Date.now()
而不是根据这个随机谷歌结果使用new Date()
。
我不知道为什么这很重要,也不知道我怎么知道这一点(欢迎解释),但这是根本原因。 我现在甚至不需要原型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.