DataMapper Dates
Forgive me if this is a simple answer.
But how do you get a Date from a DataMapper proper开发者_Go百科ty. For example:
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
You can access it with the functions from http://ruby-doc.org/core/classes/DateTime.html
For example:
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.strftime(fmt='%F %T') end
will return a date formatted YYYY-MM-DD HH:MM:SS
Does that help?
Or indeed
test.created_at.to_time
returns a date such as 2011-07-14 00:09:32 +0100
, including the offset.
Or
test.created_at.strftime("%c")
returns a date defined in the local format, such as Thu Jul 14 00:09:32 2011
.
Or either of
test.created_at.iso8601
test.created_at.to_s
returns a date in ISO 8601 format, such as 2011-07-14T00:09:32+01:00
.
Oh, and it isn't necessary to specify fmt=
; you can do
test.created_at.strftime("%F %T")
However, if you just want the date, you can do
test.created_at.to_date.to_s
which returns "2011-07-14"
.
Bear in mind, also, that you can use created_on
, if you only want to store a Date, and never a DateTime.
精彩评论