класс Date
Константы
- DATE_FORMATS
Атрибуты
Публичные методы класса
# File activesupport/lib/active_support/core_ext/date/calculations.rb, line 17 def beginning_of_week Thread.current[:beginning_of_week] || beginning_of_week_default || :monday end
Возвращает начало недели (например, :понедельник) для текущего запроса, если оно было установлено (через ::beginning_of_week=). Если Date.beginning_of_week не было установлено для текущего запроса, возвращает начало недели, указанное в config.beginning_of_week. Если config.beginning_of_week не был указан, возвращает :понедельник.
# File activesupport/lib/active_support/core_ext/date/calculations.rb, line 25 def beginning_of_week=(week_start) Thread.current[:beginning_of_week] = find_beginning_of_week!(week_start) end
Устанавливает Date.beginning_of_week на начало недели (например, :понедельник) для текущего запроса/потока.
Этот метод принимает любые из следующих символов дней недели: :понедельник, :вторник, :среда, :четверг, :пятница, :суббота, :воскресенье
# File activesupport/lib/active_support/core_ext/date/calculations.rb, line 46 def current ::Time.zone ? ::Time.zone.today : ::Date.today end
Возвращает Time.zone.today, когда Time.zone или config.time_zone установлены, в противном случае просто возвращает Date.today.
# File activesupport/lib/active_support/core_ext/date/calculations.rb, line 30
def find_beginning_of_week!(week_start)
raise ArgumentError, "Invalid beginning of week: #{week_start}" unless ::Date::DAYS_INTO_WEEK.key?(week_start)
week_start
end Возвращает символ дня начала недели (например, :понедельник), или вызывает ArgumentError для неверного символа дня.
# File activesupport/lib/active_support/core_ext/date/calculations.rb, line 41 def tomorrow ::Date.current.tomorrow end
Возвращает новый Date, представляющий дату через 1 день после сегодняшней (т.е. дату завтрашнего дня).
# File activesupport/lib/active_support/core_ext/date/calculations.rb, line 36 def yesterday ::Date.current.yesterday end
Возвращает новый Date, представляющий дату 1 день назад (т.е. дату вчерашнего дня).
Методы Публичного Экземпляра
# File activesupport/lib/active_support/core_ext/date/acts_like.rb, line 5 def acts_like_date? true end
Использует тип «утиная типизация» как класс типа Date. См. Object#acts_like?.
# File activesupport/lib/active_support/core_ext/date/calculations.rb, line 110 def advance(options) options = options.dup d = self d = d >> options.delete(:years) * 12 if options[:years] d = d >> options.delete(:months) if options[:months] d = d + options.delete(:weeks) * 7 if options[:weeks] d = d + options.delete(:days) if options[:days] d end
Обеспечивает точные вычисления Date для лет, месяцев и дней. Параметр options принимает хэш с любым из этих ключей: :years, :months, :weeks, :days.
# File activesupport/lib/active_support/core_ext/date/calculations.rb, line 125
def change(options)
::Date.new(
options.fetch(:year, year),
options.fetch(:month, month),
options.fetch(:day, day)
)
end Возвращает новый Date, где один или несколько элементов были изменены в соответствии с параметром options. Параметр options — это хэш с комбинацией этих ключей: :year, :month, :day.
Date.new(2007, 5, 12).change(day: 1) # => Date.new(2007, 5, 1) Date.new(2007, 5, 12).change(year: 2005, month: 1) # => Date.new(2005, 1, 12)
# File activesupport/lib/active_support/core_ext/date/calculations.rb, line 134
def compare_with_coercion(other)
if other.is_a?(Time)
to_datetime <=> other
else
compare_without_coercion(other)
end
end Позволяет сравнивать Date с Time, преобразуя их в DateTime и используя <=> оттуда.
# File activesupport/lib/active_support/core_ext/date/calculations.rb, line 83 def end_of_day in_time_zone.end_of_day end
Преобразует Date в Time (или DateTime, если необходимо) с частью времени, установленной в конец дня (23:59:59).
# File activesupport/lib/active_support/core_ext/date/conversions.rb, line 67
def readable_inspect
strftime("%a, %d %b %Y")
end Переопределяет метод inspect по умолчанию на удобочитаемый, например, «Пн, 21 фев 2005 г.»
# File activesupport/lib/active_support/core_ext/date/calculations.rb, line 59 def since(seconds) in_time_zone.since(seconds) end
Преобразует Date в Time (или DateTime, если необходимо) с частью времени, установленной в начало дня (0:00), а затем добавляет указанное количество секунд.
# File activesupport/lib/active_support/core_ext/date/conversions.rb, line 52
def to_formatted_s(format = :default)
if formatter = DATE_FORMATS[format]
if formatter.respond_to?(:call)
formatter.call(self).to_s
else
strftime(formatter)
end
else
to_default_s
end
end Преобразовать в отформатированную строку. См. DATE_FORMATS для предопределённых форматов.
Этот метод является псевдонимом для to_s.
date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007 date.to_formatted_s(:db) # => "2007-11-10" date.to_s(:db) # => "2007-11-10" date.to_formatted_s(:short) # => "10 Nov" date.to_formatted_s(:number) # => "20071110" date.to_formatted_s(:long) # => "November 10, 2007" date.to_formatted_s(:long_ordinal) # => "November 10th, 2007" date.to_formatted_s(:rfc822) # => "10 Nov 2007" date.to_formatted_s(:iso8601) # => "2007-11-10"
Добавление собственных форматов дат в #to_formatted_s
Вы можете добавить свои собственные форматы в хеш Date::DATE_FORMATS. Используйте имя формата в качестве ключа хеша и строку strftime или экземпляр Proc, принимающий дату в качестве аргумента, в качестве значения.
# config/initializers/date_formats.rb
Date::DATE_FORMATS[:month_and_year] = '%B %Y'
Date::DATE_FORMATS[:short_ordinal] = ->(date) { date.strftime("%B #{date.day.ordinalize}") }
# File activesupport/lib/active_support/core_ext/date/conversions.rb, line 82
def to_time(form = :local)
raise ArgumentError, "Expected :local or :utc, got #{form.inspect}." unless [:local, :utc].include?(form)
::Time.send(form, year, month, day)
end Преобразует экземпляр Date в Time, где время устанавливается в начало дня. Часовой пояс может быть :local или :utc (по умолчанию :local).
date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007 date.to_time # => 2007-11-10 00:00:00 0800 date.to_time(:local) # => 2007-11-10 00:00:00 0800 date.to_time(:utc) # => 2007-11-10 00:00:00 UTC
# File activesupport/lib/active_support/core_ext/date/conversions.rb, line 92 def xmlschema in_time_zone.xmlschema end
Возвращает строку, которая представляет время в используемом часовом поясе в виде DateTime, определённого XML Schema:
date = Date.new(2015, 05, 23) # => Sat, 23 May 2015 date.xmlschema # => "2015-05-23T00:00:00+04:00"
© 2004–2018 David Heinemeier Hansson
Licensed under the MIT License.