【问题标题】:How to save time along with user enter date in timestamp in rails如何与用户在 Rails 中的时间戳中输入日期一起节省时间
【发布时间】:2015-11-19 05:17:18
【问题描述】:

使用时间戳来保存日期和时间。用户只输入日期,我希望在保存时间之前也附上这个。

默认时间戳添加时间 00:00:00

["end_date", "2015-11-30 00:00:00"]

我希望我添加时间 23:59:59,它看起来像这样

["end_date", "2015-11-30 23:59:59"]

【问题讨论】:

    标签: mysql ruby-on-rails ruby timestamp


    【解决方案1】:
    pry(main)> Date.parse("2015-11-30").beginning_of_day.to_s
    => "2015-11-30 00:00:00 -0800"
    
    pry(main)> Date.parse("2015-11-30").end_of_day.to_s
    => "2015-11-30 23:59:59 -0800"
    

    【讨论】:

      【解决方案2】:

      你应该在模型中使用它

      before_create :set_end_date
      
      def set_end_date
         "#{self.end_date} 00:00:00".to_time.to_formatted_s(:db)
      end
      

      你会得到这样的回复:2015-11-30 00:00:00

      如果您添加 23:00:00,则使用此:

      "#{self.end_date} 23:59:59".to_time.to_formatted_s(:db)
      

      然后你会得到类似的回复:2015-11-30 23:59:59

      更多格式,你应该参考这个document

      【讨论】:

        猜你喜欢
        • 2011-10-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-05
        • 2014-02-22
        • 1970-01-01
        • 2018-05-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多