工厂女孩时间戳问题

时间:2012-02-27 11:32:22

标签: ruby-on-rails factory-bot

我使用以下代码生成3个模拟:

  # today is 27.02
  order1 = Factory(:order, :created_at => Date.yesterday) # created_all is 25.02?
  order2 = Factory(:order, :quantity => 2, :created_at => Date.today) # created_all is 26.02??
  order3 = Factory(:order, :created_at => Date.today) # created_all is 26.02???

为了正确设置日期,我使用:

  order1 = Factory(:order, :created_at => 1.days.ago)
  order2 = Factory(:order, :quantity => 2, :created_at => Time.now)
  order3 = Factory(:order, :created_at => Time.now)

知道Date.today和Time.now之间的差异是什么?

谢谢,

1 个答案:

答案 0 :(得分:5)

首先,它们是不同类的实例,并代表不同的信息: 日期仅包含日期信息,时间包含所有日期,时间和时区信息

>> Date.today
 => #<Date: 2012-02-27 (4911969/2,0,2299161)> 
>> Time.now
 => 2012-02-27 14:14:22 +0200 

在您的示例中,Date.today和Time.now将被类型转换为db中的类型(日期或时间)

>> Time.now
 => 2012-02-27 14:14:22 +0200 
>> Time.now.to_date
 => #<Date: 2012-02-27 (4911969/2,0,2299161)> 
>> Time.now.to_date.to_time
 => 2012-02-27 00:00:00 +0200