Class: Java::JavaUtil::Date
Constant Summary collapse
- MILLIS_PER_DAY =
The millisecond-to-day conversion factor.
(60 * 60 * 1000) * 24
Class Method Summary collapse
-
.from_ruby_date(date) ⇒ Date
Converts a Ruby Date or DateTime to a Java Date.
Instance Method Summary collapse
-
#to_ruby_date ⇒ DateTime
Converts this Java Date to a Ruby DateTime.
Class Method Details
.from_ruby_date(date) ⇒ Date
Converts a Ruby Date or DateTime to a Java Date.
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
# File 'lib/jinx/import/java.rb', line 159 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_date ⇒ DateTime
Converts this Java Date to a Ruby DateTime.
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 |
# File 'lib/jinx/import/java.rb', line 136 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 |