如何在 JavaScript 中输出 ISO 8601 格式的字符串?
我有一个 Date
对象。 如何呈现以下代码段的 title
部分?
<abbr title="2010-04-02T14:12:07">A couple days ago</abbr>
我有来自另一个库的“相对时间”部分。
我已经尝试了以下操作:
function isoDate(msSinceEpoch) {
var d = new Date(msSinceEpoch);
return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T' +
d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();
}
但这给了我:
"2010-4-2T3:19"
I have a Date
object. How do I render the title
portion of the following snippet?
<abbr title="2010-04-02T14:12:07">A couple days ago</abbr>
I have the "relative time in words" portion from another library.
I've tried the following:
function isoDate(msSinceEpoch) {
var d = new Date(msSinceEpoch);
return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T' +
d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();
}
But that gives me:
"2010-4-2T3:19"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(16)
已经有一个名为
toISOString( )
:如果不知何故,你在浏览器不支持它,我已经帮您解决了:
There is already a function called
toISOString()
:If, somehow, you're on a browser that doesn't support it, I've got you covered:
请参阅页面上的最后一个示例 https://developer.mozilla.org/en/Core_JavaScript_1 .5_Reference:Global_Objects:日期:
See the last example on page https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Date:
注意:截至 2022 年 3 月,此答案仍在获得投票。 moment.js 库是 已弃用。这是两个主要的替代方案: Luxon 和 Day.js,其他内容在弃用链接中提到。
卢克森
Day.js
我使用 Day.js 因为大小差异,但 Luxon 更容易处理。
网络上几乎每个 to-ISO 方法都会在输出字符串之前通过转换为“Z”ulu 时间 (UTC) 来删除时区信息。浏览器的本机 .toISOString() 也会删除时区信息。
这会丢弃有价值的信息,因为服务器或收件人始终可以将完整的 ISO 日期转换为祖鲁时间或所需的任何时区,同时仍获取发件人的时区信息。
我遇到的最佳解决方案是使用 Moment.js javascript 库并使用以下代码:
获取包含时区信息和毫秒的当前 ISO 时间
获取包含时区信息但不包含毫秒的本机 JavaScript Date 对象的 ISO 时间
这可以与 Date.js 结合使用来获取像 Date.today() 这样的函数,其结果可以传递给 moment。
像这样格式化的日期字符串与 JSON 兼容,并且非常适合存储到数据库中。 Python 和 C# 似乎很喜欢它。
Note: This answer is still getting upvotes as of 2022-03. The moment.js library is deprecated. These are the two main alternatives: Luxon and Day.js, others are mentioned in the deprecation link.
Luxon
Day.js
I use Day.js because of the size difference, but Luxon is easier to deal with.
Almost every to-ISO method on the web drops the timezone information by applying a convert to "Z"ulu time (UTC) before outputting the string. Browser's native .toISOString() also drops timezone information.
This discards valuable information, as the server, or recipient, can always convert a full ISO date to Zulu time or whichever timezone it requires, while still getting the timezone information of the sender.
The best solution I've come across is to use the Moment.js javascript library and use the following code:
To get the current ISO time with timezone information and milliseconds
To get the ISO time of a native JavaScript Date object with timezone information but without milliseconds
This can be combined with Date.js to get functions like Date.today() whose result can then be passed to moment.
A date string formatted like this is JSON compilant, and lends itself well to get stored into a database. Python and C# seem to like it.
提出的问题是精度降低的 ISO 格式。瞧:
假设需要尾随 Z,否则就省略。
The question asked was ISO format with reduced precision. Voila:
Assuming the trailing Z is wanted, otherwise just omit.
最短,但 Internet Explorer 8 及更早版本不支持:
Shortest, but not supported by Internet Explorer 8 and earlier:
如果您不需要支持 IE7,以下是一个很棒、简洁的技巧:
If you don't need to support IE7, the following is a great, concise hack:
我通常不想显示 UTC 日期,因为客户不喜欢在头脑中进行转换。要显示本地 ISO 日期,我使用以下函数:
上面的函数省略了时区偏移信息(除非本地时间恰好是 UTC),所以我使用下面的函数来显示本地偏移一个位置。如果您希望每次都显示偏移量,您还可以将其输出附加到上述函数的结果中:
toLocalIsoString
使用pad
。如果需要,它的工作方式几乎与任何 pad 功能类似,但为了完整起见,我使用的是:I typically don't want to display a UTC date since customers don't like doing the conversion in their head. To display a local ISO date, I use the function:
The function above omits time zone offset information (except if local time happens to be UTC), so I use the function below to show the local offset in a single location. You can also append its output to results from the above function if you wish to show the offset in each and every time:
toLocalIsoString
usespad
. If needed, it works like nearly any pad function, but for the sake of completeness this is what I use:toISOString 的问题在于它仅以“Z”形式给出日期时间。
ISO-8601 还定义了以小时和分钟为单位的时区差异的日期时间,其形式如 2016-07-16T19:20:30+5:30(当时区领先于 UTC 时)和 2016-07-16T19:20:30-01 :00(当时区晚于 UTC 时)。
我认为使用另一个插件 moment.js 来完成这样一个小任务不是一个好主意,特别是当您可以通过几行代码获得它时。
获得以小时和分钟为单位的时区偏移后,您可以附加到日期时间字符串。
我写了一篇关于它的博客文章: http: //usefulangle.com/post/30/javascript-get-date-time-with-offset-hours-mins
The problem with toISOString is that it gives datetime only as "Z".
ISO-8601 also defines datetime with timezone difference in hours and minutes, in the forms like 2016-07-16T19:20:30+5:30 (when timezone is ahead UTC) and 2016-07-16T19:20:30-01:00 (when timezone is behind UTC).
I don't think it is a good idea to use another plugin, moment.js for such a small task, especially when you can get it with a few lines of code.
Once you have the timezone offset in hours and minutes, you can append to a datetime string.
I wrote a blog post on it : http://usefulangle.com/post/30/javascript-get-date-time-with-offset-hours-minutes
“T”后面缺少一个“+”
。
对于前导零,您可以使用 这里:
像这样使用它:
There is a '+' missing after the 'T'
should do it.
For the leading zeros you could use this from here:
Using it like this:
我想我找到了一个更好的解决方案:
根据 wiki 页面 加拿大使用 ISO 8601 作为官方日期格式,因此我们可以安全地使用它。
I think I have found an even better solution:
According to the wiki page Canada uses ISO 8601 as the official date format, therefore we can safely use this.
我能够用很少的代码得到下面的输出。
输出:
I was able to get below output with very less code.
Output:
我只想使用这个小扩展来
Date
- http:// /blog.stevenlevithan.com/archives/date-time-formatI would just use this small extension to
Date
- http://blog.stevenlevithan.com/archives/date-time-format我在某处找到了 Stack Overflow 的基础知识(我相信它是其他一些 Stack Exchange 代码高尔夫的一部分),并且我对其进行了改进,使其也可以在 Internet Explorer 10 或更早版本上运行。它很丑陋,但它可以完成工作。
I found the basics on Stack Overflow somewhere (I believe it was part of some other Stack Exchange code golfing), and I improved it so it works on Internet Explorer 10 or earlier as well. It's ugly, but it gets the job done.
用一些糖和现代语法来扩展肖恩伟大而简洁的答案:
然后例如。
To extend Sean's great and concise answer with some sugar and modern syntax:
Then eg.
简短的一个:
A short one: