在Rails中设置标准日期/时间格式

时间:2013-11-20 21:28:24

标签: ruby-on-rails datetime

在Rails中创建标准日期/时间格式的最佳做法是什么?我们有类似的陈述:

def get_formatted_due_date
    self.DueDate.try { |d| d.strftime("%m/%d/%y %l:%M%P")}
end

ScheduledSendDate.try(:strftime, "%m/%d/%y %l:%M%P")

然而,这种解决方案似乎并不干燥或优雅。有没有办法设置默认格式并一遍又一遍地使用它?

更新: 我添加了一个config / initializers / date_and_time_format.rb文件:

Time::DATE_FORMATS[:my_format] = '%m/%d/%y %l:%M%P' # 02/22/13 12:30pm

在代码中,我转而使用:

def get_formatted_due_date
    self.DueDate.try { |d| d.strftime(:my_format)}
end

ScheduledSendDate.try(:to_s, :my_format)

这似乎就是这样做的。

1 个答案:

答案 0 :(得分:1)

DateTime.new(params[:year],params[:month],params[:day])

require 'date'
date = DateTime.civil( *params.values_at( :year, :month, :day ) )

或时区1 ......

Set the time zone of the TimeWithZone instance
Time.zone = 'Central Time (US & Canada)'

Get current time using the time zone you set
Time.zone.now

Convert from unix timestamp back to time format using the time zone you set
Time.zone.at(1364046539)

Convert from unix timestamp back to time format using the time zone you set,
and the required string format => "03/23/13 09:48 AM"
Time.at(1364046539).in_time_zone("Eastern Time (US & Canada)").strftime("%m/%d/%y %I:%M %p")

无论如何我还没有触及轨道多年来啊哈告诉我它是不起作用还是它不是想要你的意思

相关问题