日期时间解析未按预期工作

发布于 2024-10-06 15:44:38 字数 260 浏览 0 评论 0原文

我的 Ruby 代码看起来有点像这样。

str = 2010-12-02_12-10-26
puts str
puts DateTime.parse(str, "%Y-%m-%d_%H-%M-%S")

我希望从解析中获得实际时间。相反,我得到这样的输出...

2010-12-02_12-10-26
2010-12-02T00:00:00+00:00

我如何也解析时间?

I have Ruby code that looks vaguely like this.

str = 2010-12-02_12-10-26
puts str
puts DateTime.parse(str, "%Y-%m-%d_%H-%M-%S")

I expected to get the actual time from the parse. Instead, I'm getting output like this...

2010-12-02_12-10-26
2010-12-02T00:00:00+00:00

How do I get the time parsed in as well?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

捎一片雪花 2024-10-13 15:44:38

这有效:

str = "2010-12-02_12-10-26"
puts str
puts DateTime.strptime(str, "%Y-%m-%d_%H-%M-%S")

此示例位于 Codepad 上。

根据文档 解析

通过解析字符串创建一个新的 DateTime 对象,而不指定格式。

和strptime:

通过根据指定格式解析字符串来创建新的 DateTime 对象。

This works:

str = "2010-12-02_12-10-26"
puts str
puts DateTime.strptime(str, "%Y-%m-%d_%H-%M-%S")

This example on Codepad.

According to the documentation parse:

Create a new DateTime object by parsing from a String, without specifying the format.

And strptime:

Create a new DateTime object by parsing from a String according to a specified format.

白衬杉格子梦 2024-10-13 15:44:38

使用 strptime 而不是 parse

puts DateTime.strptime(str, "%Y-%m-%d_%H-%M-%S")

Use strptime instead of parse

puts DateTime.strptime(str, "%Y-%m-%d_%H-%M-%S")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文