Class: Java::JavaUtil::Date

Inherits:
Object show all
Defined in:
lib/caruby/import/java.rb

Constant Summary collapse

MILLIS_PER_DAY =

The millisecond-to-day conversion factor.

(60 * 60 * 1000) * 24

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_ruby_date(date) ⇒ Date

Converts a Ruby Date or DateTime to a Java Date.

Parameters:

  • date (::Date, DateTime)

    the Ruby date

Returns:

  • (Date)

    the Java date



211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/caruby/import/java.rb', line 211

def self.from_ruby_date(date)
  return if date.nil?
  # DateTime has time attributes, Date doesn't
  if DateTime === date then
    hour, min, sec = date.hour, date.min, date.sec
  else
    hour = min = sec = 0
  end
  # the Ruby time
  rtime = Time.local(sec, min, hour, date.day, date.mon, date.year, nil, nil, nil, nil)
  # millis since epoch
  millis = (rtime.to_f * 1000).truncate
  # the Java date factory
  calendar = java.util.Calendar.instance
  calendar.setTimeInMillis(millis)
  jtime = calendar.getTime
  # the daylight time flag
  isdt = calendar.timeZone.inDaylightTime(jtime)
  return jtime unless isdt
  # adjust the Ruby time for DST
  rtime = Time.local(sec, min, hour, date.day, date.mon, date.year, nil, nil, isdt, nil)
  millis = (rtime.to_f * 1000).truncate
  calendar.setTimeInMillis(millis)
  calendar.getTime
end

Instance Method Details

#to_ruby_dateDateTime

Converts this Java Date to a Ruby DateTime.

Returns:



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/caruby/import/java.rb', line 188

def to_ruby_date
  calendar = java.util.Calendar.instance
  calendar.setTime(self)
  secs = calendar.timeInMillis.to_f / 1000
  # millis since epoch
  time = Time.at(secs)
  # convert UTC timezone millisecond offset to Rational fraction of a day
  offset_millis = calendar.timeZone.getOffset(calendar.timeInMillis).to_f
  if offset_millis.zero? then
    offset = 0
  else
    offset_days = offset_millis / MILLIS_PER_DAY
    offset_fraction = 1 / offset_days
    offset = Rational(1, offset_fraction)
  end
  # convert to DateTime
  DateTime.civil(time.year, time.mon, time.day, time.hour, time.min, time.sec, offset)
end