Class: DateTime

Inherits:
Object show all
Includes:
DateAndTime::Compatibility
Defined in:
lib/active_support/core_ext/date_time/blank.rb,
lib/active_support/core_ext/object/json.rb,
lib/active_support/core_ext/date_time/acts_like.rb,
lib/active_support/core_ext/date_time/conversions.rb,
lib/active_support/core_ext/date_time/calculations.rb,
lib/active_support/core_ext/date_time/compatibility.rb

Overview

:nodoc:

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.civil_from_format(utc_or_local, year, month = 1, day = 1, hour = 0, min = 0, sec = 0) ⇒ Object

Returns DateTime with local offset for given year if format is local else offset is zero.

DateTime.civil_from_format :local, 2012
# => Sun, 01 Jan 2012 00:00:00 +0300
DateTime.civil_from_format :local, 2012, 12, 17
# => Mon, 17 Dec 2012 00:00:00 +0000


73
74
75
76
77
78
79
80
# File 'lib/active_support/core_ext/date_time/conversions.rb', line 73

def self.civil_from_format(utc_or_local, year, month = 1, day = 1, hour = 0, min = 0, sec = 0)
  if utc_or_local.to_sym == :local
    offset = ::Time.local(year, month, day).utc_offset.to_r / 86400
  else
    offset = 0
  end
  civil(year, month, day, hour, min, sec, offset)
end

.currentObject

Returns Time.zone.now.to_datetime when Time.zone or config.time_zone are set, otherwise returns Time.now.to_datetime.



10
11
12
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 10

def current
  ::Time.zone ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime
end

Instance Method Details

#<=>(other) ⇒ Object

Layers additional behavior on DateTime#<=> so that Time and ActiveSupport::TimeWithZone instances can be compared with a DateTime.



208
209
210
211
212
213
214
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 208

def <=>(other)
  if other.respond_to? :to_datetime
    super other.to_datetime rescue nil
  else
    super
  end
end

#acts_like_date?Boolean

Duck-types as a Date-like class. See Object#acts_like?.

Returns:

  • (Boolean)


8
9
10
# File 'lib/active_support/core_ext/date_time/acts_like.rb', line 8

def acts_like_date?
  true
end

#acts_like_time?Boolean

Duck-types as a Time-like class. See Object#acts_like?.

Returns:

  • (Boolean)


13
14
15
# File 'lib/active_support/core_ext/date_time/acts_like.rb', line 13

def acts_like_time?
  true
end

#advance(options) ⇒ Object

Uses Date to provide precise Time calculations for years, months, and days. The options parameter takes a hash with any of these keys: :years, :months, :weeks, :days, :hours, :minutes, :seconds.

Just like Date#advance, increments are applied in order of time units from largest to smallest. This order can affect the result around the end of a month.



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 82

def advance(options)
  unless options[:weeks].nil?
    options[:weeks], partial_weeks = options[:weeks].divmod(1)
    options[:days] = options.fetch(:days, 0) + 7 * partial_weeks
  end

  unless options[:days].nil?
    options[:days], partial_days = options[:days].divmod(1)
    options[:hours] = options.fetch(:hours, 0) + 24 * partial_days
  end

  d = to_date.advance(options)
  datetime_advanced_by_date = change(year: d.year, month: d.month, day: d.day)
  seconds_to_advance = \
    options.fetch(:seconds, 0) +
    options.fetch(:minutes, 0) * 60 +
    options.fetch(:hours, 0) * 3600

  if seconds_to_advance.zero?
    datetime_advanced_by_date
  else
    datetime_advanced_by_date.since(seconds_to_advance)
  end
end

#ago(seconds) ⇒ Object

Returns a new DateTime representing the time a number of seconds ago. Do not use this method in combination with x.months, use months_ago instead!



109
110
111
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 109

def ago(seconds)
  since(-seconds)
end

#as_json(options = nil) ⇒ Object

:nodoc:



215
216
217
218
219
220
221
# File 'lib/active_support/core_ext/object/json.rb', line 215

def as_json(options = nil) # :nodoc:
  if ActiveSupport::JSON::Encoding.use_standard_json_time_format
    xmlschema(ActiveSupport::JSON::Encoding.time_precision)
  else
    strftime("%Y/%m/%d %H:%M:%S %z")
  end
end

#beginning_of_dayObject Also known as: midnight, at_midnight, at_beginning_of_day

Returns a new DateTime representing the start of the day (0:00).



122
123
124
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 122

def beginning_of_day
  change(hour: 0)
end

#beginning_of_hourObject Also known as: at_beginning_of_hour

Returns a new DateTime representing the start of the hour (hh:00:00).



146
147
148
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 146

def beginning_of_hour
  change(min: 0)
end

#beginning_of_minuteObject Also known as: at_beginning_of_minute

Returns a new DateTime representing the start of the minute (hh:mm:00).



158
159
160
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 158

def beginning_of_minute
  change(sec: 0)
end

#blank?false

No DateTime is ever blank:

DateTime.now.blank? # => false

Returns:

  • (false)


11
12
13
# File 'lib/active_support/core_ext/date_time/blank.rb', line 11

def blank?
  false
end

#change(options) ⇒ Object

Returns a new DateTime where one or more of the elements have been changed according to the options parameter. The time options (:hour, :min, :sec) reset cascadingly, so if only the hour is passed, then minute and sec is set to 0. If the hour and minute is passed, then sec is set to 0. The options parameter takes a hash with any of these keys: :year, :month, :day, :hour, :min, :sec, :offset, :start.

DateTime.new(2012, 8, 29, 22, 35, 0).change(day: 1)              # => DateTime.new(2012, 8, 1, 22, 35, 0)
DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1)  # => DateTime.new(1981, 8, 1, 22, 35, 0)
DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => DateTime.new(1981, 8, 29, 0, 0, 0)

Raises:

  • (ArgumentError)


51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 51

def change(options)
  if new_nsec = options[:nsec]
    raise ArgumentError, "Can't change both :nsec and :usec at the same time: #{options.inspect}" if options[:usec]
    new_fraction = Rational(new_nsec, 1000000000)
  else
    new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000))
    new_fraction = Rational(new_usec, 1000000)
  end

  raise ArgumentError, "argument out of range" if new_fraction >= 1

  ::DateTime.civil(
    options.fetch(:year, year),
    options.fetch(:month, month),
    options.fetch(:day, day),
    options.fetch(:hour, hour),
    options.fetch(:min, options[:hour] ? 0 : min),
    options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec) + new_fraction,
    options.fetch(:offset, offset),
    options.fetch(:start, start)
  )
end

#end_of_dayObject Also known as: at_end_of_day

Returns a new DateTime representing the end of the day (23:59:59).



140
141
142
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 140

def end_of_day
  change(hour: 23, min: 59, sec: 59, usec: Rational(999999999, 1000))
end

#end_of_hourObject Also known as: at_end_of_hour

Returns a new DateTime representing the end of the hour (hh:59:59).



152
153
154
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 152

def end_of_hour
  change(min: 59, sec: 59, usec: Rational(999999999, 1000))
end

#end_of_minuteObject Also known as: at_end_of_minute

Returns a new DateTime representing the end of the minute (hh:mm:59).



164
165
166
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 164

def end_of_minute
  change(sec: 59, usec: Rational(999999999, 1000))
end

#formatted_offset(colon = true, alternate_utc_string = nil) ⇒ Object

Returns a formatted string of the offset from UTC, or an alternative string if the time zone is already UTC.

datetime = DateTime.civil(2000, 1, 1, 0, 0, 0, Rational(-6, 24))
datetime.formatted_offset         # => "-06:00"
datetime.formatted_offset(false)  # => "-0600"


55
56
57
# File 'lib/active_support/core_ext/date_time/conversions.rb', line 55

def formatted_offset(colon = true, alternate_utc_string = nil)
  utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
end

#localtime(utc_offset = nil) ⇒ Object Also known as: getlocal

Returns a Time instance of the simultaneous time in the system timezone.



170
171
172
173
174
175
176
177
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 170

def localtime(utc_offset = nil)
  utc = new_offset(0)

  Time.utc(
    utc.year, utc.month, utc.day,
    utc.hour, utc.min, utc.sec + utc.sec_fraction
  ).getlocal(utc_offset)
end

#middle_of_dayObject Also known as: midday, noon, at_midday, at_noon, at_middle_of_day

Returns a new DateTime representing the middle of the day (12:00)



130
131
132
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 130

def middle_of_day
  change(hour: 12)
end

#nsecObject

Returns the fraction of a second as nanoseconds



98
99
100
# File 'lib/active_support/core_ext/date_time/conversions.rb', line 98

def nsec
  (sec_fraction * 1_000_000_000).to_i
end

#readable_inspectObject Also known as: inspect

Overrides the default inspect method with a human readable one, e.g., “Mon, 21 Feb 2005 14:30:00 +0000”.



60
61
62
# File 'lib/active_support/core_ext/date_time/conversions.rb', line 60

def readable_inspect
  to_fs(:rfc822)
end

#seconds_since_midnightObject

Returns the number of seconds since 00:00:00.

DateTime.new(2012, 8, 29,  0,  0,  0).seconds_since_midnight # => 0
DateTime.new(2012, 8, 29, 12, 34, 56).seconds_since_midnight # => 45296
DateTime.new(2012, 8, 29, 23, 59, 59).seconds_since_midnight # => 86399


20
21
22
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 20

def seconds_since_midnight
  sec + (min * 60) + (hour * 3600)
end

#seconds_until_end_of_dayObject

Returns the number of seconds until 23:59:59.

DateTime.new(2012, 8, 29,  0,  0,  0).seconds_until_end_of_day # => 86399
DateTime.new(2012, 8, 29, 12, 34, 56).seconds_until_end_of_day # => 41103
DateTime.new(2012, 8, 29, 23, 59, 59).seconds_until_end_of_day # => 0


29
30
31
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 29

def seconds_until_end_of_day
  end_of_day.to_i - to_i
end

#since(seconds) ⇒ Object Also known as: in

Returns a new DateTime representing the time a number of seconds since the instance time. Do not use this method in combination with x.months, use months_since instead!



116
117
118
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 116

def since(seconds)
  self + Rational(seconds, 86400)
end

#subsecObject

Returns the fraction of a second as a Rational

DateTime.new(2012, 8, 29, 0, 0, 0.5).subsec # => (1/2)


36
37
38
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 36

def subsec
  sec_fraction
end

#to_fObject

Converts self to a floating-point number of seconds, including fractional microseconds, since the Unix epoch.



83
84
85
# File 'lib/active_support/core_ext/date_time/conversions.rb', line 83

def to_f
  seconds_since_unix_epoch.to_f + sec_fraction
end

#to_fs(format = :default) ⇒ Object Also known as: to_formatted_s

Convert to a formatted string. See Time::DATE_FORMATS for predefined formats.

This method is aliased to to_formatted_s.

Examples

datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0)   # => Tue, 04 Dec 2007 00:00:00 +0000

datetime.to_fs(:db)            # => "2007-12-04 00:00:00"
datetime.to_formatted_s(:db)   # => "2007-12-04 00:00:00"
datetime.to_fs(:number)        # => "20071204000000"
datetime.to_fs(:short)         # => "04 Dec 00:00"
datetime.to_fs(:long)          # => "December 04, 2007 00:00"
datetime.to_fs(:long_ordinal)  # => "December 4th, 2007 00:00"
datetime.to_fs(:rfc822)        # => "Tue, 04 Dec 2007 00:00:00 +0000"
datetime.to_fs(:iso8601)       # => "2007-12-04T00:00:00+00:00"

Adding your own datetime formats to to_fs

DateTime formats are shared with Time. You can add your own to the Time::DATE_FORMATS hash. Use the format name as the hash key and either a strftime string or Proc instance that takes a time or datetime argument as the value.

# config/initializers/time_formats.rb
Time::DATE_FORMATS[:month_and_year] = '%B %Y'
Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }


35
36
37
38
39
40
41
# File 'lib/active_support/core_ext/date_time/conversions.rb', line 35

def to_fs(format = :default)
  if formatter = ::Time::DATE_FORMATS[format]
    formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
  else
    to_s
  end
end

#to_iObject

Converts self to an integer number of seconds since the Unix epoch.



88
89
90
# File 'lib/active_support/core_ext/date_time/conversions.rb', line 88

def to_i
  seconds_since_unix_epoch.to_i
end

#to_timeObject

Either return an instance of Time with the same UTC offset as self or an instance of Time representing the same time in the local system timezone depending on the setting of on the setting of ActiveSupport.to_time_preserves_timezone.



15
16
17
# File 'lib/active_support/core_ext/date_time/compatibility.rb', line 15

def to_time
  preserve_timezone ? getlocal(utc_offset) : getlocal
end

#usecObject

Returns the fraction of a second as microseconds



93
94
95
# File 'lib/active_support/core_ext/date_time/conversions.rb', line 93

def usec
  (sec_fraction * 1_000_000).to_i
end

#utcObject Also known as: getgm, getutc, gmtime

Returns a Time instance of the simultaneous time in the UTC timezone.

DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24))     # => Mon, 21 Feb 2005 10:11:12 -0600
DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)).utc # => Mon, 21 Feb 2005 16:11:12 UTC


184
185
186
187
188
189
190
191
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 184

def utc
  utc = new_offset(0)

  Time.utc(
    utc.year, utc.month, utc.day,
    utc.hour, utc.min, utc.sec + utc.sec_fraction
  )
end

#utc?Boolean

Returns true if offset == 0.

Returns:

  • (Boolean)


197
198
199
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 197

def utc?
  offset == 0
end

#utc_offsetObject

Returns the offset value in seconds.



202
203
204
# File 'lib/active_support/core_ext/date_time/calculations.rb', line 202

def utc_offset
  (offset * 86400).to_i
end