为什么秒转换(strptime / strftime)?

时间:2013-08-15 05:20:00

标签: ruby datetime

我正在尝试转换为Mysql时间日期时间格式,但秒不转换,只有日期看起来很好。

1.9.3-p448 :030 >  d = Date.strptime "26 Jul 2013 00:04:52 UTC", '%d %b %Y %H:%M:%S %z'
=> #<Date: 2013-07-26 ((2456500j,0s,0n),+0s,2299161j)>
1.9.3-p448 :031 > d.strftime ("%Y-%m-%d %H:%M:%S")
=> "2013-07-26 00:00:00"

3 个答案:

答案 0 :(得分:4)

您正在使用Date,它没有时间。尝试使用DateTime

irb [1.9.3]$ require "date"
=> true
irb [1.9.3]$ d = DateTime.strptime "26 Jul 2013 00:04:52 UTC", '%d %b %Y %H:%M:%S'
=> #<DateTime: 2013-07-26T00:04:52+00:00 ((2456500j,292s,0n),+0s,2299161j)>
irb [1.9.3]$  d.strftime ("%Y-%m-%d %H:%M:%S")
=> "2013-07-26 00:04:52"

答案 1 :(得分:2)

您必须使用Time class代替Date。原因Date仅包含YYYY-MM-DD之类的日期。

示例:

root@ubuntu-server:~# irb
irb(main):001:0> require 'time'
=> true
irb(main):002:0> t = Time.parse("26 Jul 2013 00:04:52 UTC")
=> Fri Jul 26 00:04:52 UTC 2013
irb(main):003:0> t.strftime("%Y-%m-%d %H:%M:%S")
=> "2013-07-26 00:04:52"  

答案 2 :(得分:1)

您使用错误的类型DateTime

1.9.3-p448 :030 >  d = DateTime.strptime "26 Jul 2013 00:04:52 UTC", '%d %b %Y %H:%M:%S %z'
=> #<DateTime: 53060389273/21600,0,2299161>
1.9.3-p448 :031 > d.strftime ("%Y-%m-%d %H:%M:%S")
=> "2013-07-26 00:04:52"