在 Ruby 中将 UTC 时间戳转换为 ISO 8601 [英] Converting UTC timestamp to ISO 8601 in Ruby

查看:61
本文介绍了在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆