在 Ruby 中将 UTC 时间戳转换为 ISO 8601

编程入门 行业动态 更新时间:2024-10-28 18:25:17
本文介绍了在 Ruby 中将 UTC 时间戳转换为 ISO 8601的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 UTC 时间戳

I have a timestamp that is in UTC

2010-10-25 23:48:46 UTC"

"2010-10-25 23:48:46 UTC"

我需要将其转换为 ISO 8601

I need to convert it into ISO 8601

2010-10-29 06:09Z"

"2010-10-29 06:09Z"

文档令人困惑 - 最简单的方法是什么?

The documentation is confusing as hell - what is the easiest way to do that?

推荐答案

我认为你在欺骗我们.

您问题的输入日期是 2010 年 10 月 25 日,而输出日期是 2010 年 10 月 29 日.打得好!

The input date to your question is the 25th of October, 2010, whilst the output is the 29th of October, 2010. Well played!

继续这个挑剔的线程:你的时间也完全不同,你错过了输出时间的秒数.

Continuing on this nit-picking thread: your times are also completely different and you're missing the seconds from the output time.

现在来看看真正的答案.

Now for the true answer.

首先要说明一点:Ruby 中的 ISO 8601 输出类似于 ISO 8601 的维基百科页面.

A little factoid first though: the ISO 8601 output in Ruby is similar to the "Combined date and time" output from ISO 8601's Wikipedia page.

你有一个字符串,所以你需要将它转换成一个 Time 对象,你可以用 to_time 来做.然后只需对该对象调用 iso8601 即可获取 ISO 8601 版本:

You've got a string and so you'll need to convert it into a Time object which you can do with to_time. Then it's simply a matter of calling iso8601 on that object to get the ISO 8601 version:

"2010-10-25 23:48:46 UTC".to_time.iso8601

to_time 方法由 Rails 提供,而 iso8601 方法由 Ruby 的标准库提供.

The to_time method is courtesy of Rails, whilst the iso8601 is courtesy of Ruby's standard library.

更多推荐

在 Ruby 中将 UTC 时间戳转换为 ISO 8601

本文发布于:2023-10-23 06:28:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1520060.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   中将   时间   Ruby   UTC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!