【问题标题】:How to include milliseconds in Time.zone.parse method如何在 Time.zone.parse 方法中包含毫秒
【发布时间】:2017-05-01 19:45:15
【问题描述】:

我正在尝试获取一个包含毫秒格式的 Time 对象:

x = Time.zone.parse("12-1-1998 00:00:00.000", "%Y-%m-%d %H:%M:%S.%3N") 

添加格式时出现错误:

undefined method `year' for "%Y-%m-%d %H:%M:%S.%3N":String (NoMethodError)

我也试过Time.zone.parse("12-1-1998 00:00:00.000"),但我明白了:

1998-01-12T00:00:00Z

我需要时间看起来像这样:

1998-01-12T00:00:00.000Z

【问题讨论】:

    标签: ruby-on-rails ruby time


    【解决方案1】:

    使用DateTime#strftime:

    datetime = DateTime.strptime("2011-05-21 04:20:46.011", "%Y-%m-%d %H:%M:%S.%L")
    datetime.strftime("%Y-%m-%dT%H:%M:%S.%LZ")
     => "2011-05-21T04:20:46.011Z"
    

    【讨论】:

    • 最后的Z 怎么样?另外,没有T,请看预期结果。 1998-01-12T00:00:00.000Z
    • @abdulahmad 您可以根据需要更改strftime的格式字符串
    • DateTime.strptime("2011-05-21 04:20:46.011", "%Y-%m-%d %H:%M:%S.%L").strftime("%Y-%m-%dT%H:%M:%S.%LZ")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 2010-12-22
    相关资源
    最近更新 更多