【问题标题】:Convert a date string to a Unix timestamp将日期字符串转换为 Unix 时间戳
【发布时间】:2010-03-15 23:14:39
【问题描述】:

我有这个日期“2010 年 3 月 15 日星期一 20:51:18 +0000”。如何将此日期转换为 Unix 时间戳?

【问题讨论】:

    标签: ruby-on-rails datetime


    【解决方案1】:
    require 'time'
    Time.parse("Mon Mar 15 20:51:18 +0000 2010").to_i
    

    【讨论】:

      【解决方案2】:

      只需在 DateTime 对象上调用“.to_i”

      【讨论】:

      • DateTime上没有to_i,你必须通过Time,即.to_time.to_i
      【解决方案3】:

      你绝对可以使用

      require 'time'
      Time.parse("Mon Mar 15 20:51:18 +0000 2010").to_i
      

      就像 user30997 和 Zepplock 说的,但是如果你有非标准时间字符串,你可能想要使用 chronic 库。

      require 'chronic'
      Chronic.parse('tomorrow').to_i
      

      它使网站上的输入字段对最终用户来说非常好。

      【讨论】:

        猜你喜欢
        • 2011-03-16
        • 2019-07-30
        • 2012-06-23
        • 2011-09-23
        • 1970-01-01
        • 2022-01-21
        • 2012-09-01
        • 1970-01-01
        相关资源
        最近更新 更多