【问题标题】:DataMapper Dates数据映射器日期
【发布时间】:2011-07-14 07:22:41
【问题描述】:

如果这是一个简单的答案,请原谅我。

但是如何从 DataMapper 属性中获取日期。例如:

require 'rubygems'
require 'sinatra'
require 'datamapper'

class Test
    include DataMapper::Resource

    property :id, Serial
    property :created_at, Date
end

get '/:id' do
    test = Test.get(1)

    test.created_at = ?
end

【问题讨论】:

    标签: ruby date sinatra datamapper


    【解决方案1】:

    您可以使用以下功能访问它 http://ruby-doc.org/core/classes/DateTime.html

    例如:

    需要'rubygems'
    需要'sinatra'
    需要“数据映射器”
    
    类测试
        包括 DataMapper::Resource
    
        属性:id,序列号
        属性:created_at,日期
    结尾
    
    得到'/:id'做
        测试 = 测试.get(1)
    
        test.created_at.strftime(fmt='%F %T')
    结尾
    

    将返回格式为 YYYY-MM-DD HH:MM:SS 的日期

    这有帮助吗?

    【讨论】:

      【解决方案2】:

      确实

      test.created_at.to_time
      

      返回一个日期,例如2011-07-14 00:09:32 +0100,包括偏移量。

      或者

      test.created_at.strftime("%c")
      

      返回以本地格式定义的日期,例如Thu Jul 14 00:09:32 2011

      或任何一个

      test.created_at.iso8601
      test.created_at.to_s
      

      返回 ISO 8601 格式的日期,例如 2011-07-14T00:09:32+01:00

      哦,没有必要指定fmt=;你可以做

      test.created_at.strftime("%F %T")
      

      但是,如果你只想要日期,你可以这样做

      test.created_at.to_date.to_s
      

      返回"2011-07-14"

      另外请记住,如果您只想存储日期而不是日期时间,则可以使用 created_on

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-20
        • 2013-06-08
        • 2014-01-06
        • 1970-01-01
        相关资源
        最近更新 更多