класс Date
Константы
- DATE_FORMATS
Атрибуты
Публичные методы класса
# File activesupport/lib/active_support/core_ext/date/calculations.rb, line 19 def beginning_of_week Thread.current[:beginning_of_week] || beginning_of_week_default || :monday end
Возвращает начало недели (например, :понедельник) для текущего запроса, если оно было установлено (через Date.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 27 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 48 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 32
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 43 def tomorrow ::Date.current.tomorrow end
Возвращает новый Date, представляющий дату на следующий день после сегодняшней (т. е. дату завтрашнего дня).
# File activesupport/lib/active_support/core_ext/date/calculations.rb, line 38 def yesterday ::Date.current.yesterday end
Возвращает новый Date, представляющий дату 1 день назад (т. е. вчерашнюю дату).
Публичные методы экземпляров
# File activesupport/lib/active_support/core_ext/date/acts_like.rb, line 7 def acts_like_date? true end
Имитирует класс Date. См. Object#acts_like?.
# File activesupport/lib/active_support/core_ext/date/calculations.rb, line 112 def advance(options) d = self d = d >> options[:years] * 12 if options[:years] d = d >> options[:months] if options[:months] d = d + options[:weeks] * 7 if options[:weeks] d = d + options[:days] if options[:days] d end
Предоставляет точные Date вычисления для лет, месяцев и дней. Параметр options принимает хеш с любыми из этих ключей: :years, :months, :weeks, :days.
# File activesupport/lib/active_support/core_ext/date/calculations.rb, line 128
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 137
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 85 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 62
def readable_inspect
strftime("%a, %d %b %Y")
end Переопределяет метод inspect на удобочитаемый, например, «Пн, 21 фев 2005 г.»
# File activesupport/lib/active_support/core_ext/date/calculations.rb, line 61 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 47
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.public_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
ПРИМЕЧАНИЕ: Временная зона :local — это временная зона Ruby процесса, т. е. ENV.
If the *application's* timezone is needed, then use +in_time_zone+ instead.
# File activesupport/lib/active_support/core_ext/date/conversions.rb, line 94 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–2020 David Heinemeier Hansson
Licensed under the MIT License.