lib/sdl4r/sdl4r.rb in sdl4r-0.9.4 vs lib/sdl4r/sdl4r.rb in sdl4r-0.9.5

- old
+ new

@@ -1,5 +1,8 @@ +#!/usr/bin/env ruby -w +# encoding: UTF-8 + #-- # Simple Declarative Language (SDL) for Ruby # Copyright 2005 Ikayzo, inc. # # This program is free software. You can distribute or modify it under the @@ -13,11 +16,10 @@ # You should have received a copy of the GNU Lesser General Public License # along with this program; if not, contact the Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #++ -require 'jcode' require 'base64' require 'bigdecimal' require 'date' # Gathers utility methods. @@ -98,11 +100,11 @@ return encoded_o # Below, we use "#{o.year}" instead of "%Y" because "%Y" always emit 4 chars at least even if # the date is before 1000. elsif o.is_a?(DateTime) || o.is_a?(Time) - milliseconds = o.is_a?(DateTime) ? get_date_milliseconds(o) : (o.usec / 10).to_i + milliseconds = get_datetime_milliseconds(o) if milliseconds == 0 if o.zone return o.strftime("#{o.year}/%m/%d %H:%M:%S%Z") else @@ -339,15 +341,25 @@ } return escaped_s end - # Returns the milliseonds part of a DateTime (by translating the +sec_fraction+ part) as an - # integer. - def get_date_milliseconds(date) - sec_fraction = date.sec_fraction() # in days - # 86400000 is the number of milliseconds in a day - return (sec_fraction * 86400000).round() + # Returns the microseconds component of the given DateTime or Time. + # DateTime and Time having vastly different behaviors between themselves or in Ruby 1.8 and 1.9, + # this method makes an attemps at getting this component out of the specified object. + # + # In particular, DateTime.sec_fraction() (which I used before) returns incorrect values in, at + # least, some revisions of Ruby 1.9. + # + def get_datetime_milliseconds(datetime) + if defined?(datetime.usec) + return (datetime.usec / 1000).round + else + # Here don't believe that we could use '%3N' to get the milliseconds directly: the "3" is + # ignored for DateTime.strftime() in Ruby 1.8. + nanoseconds = Integer(datetime.strftime("%N")) + return (nanoseconds / 1000000).round + end end end end \ No newline at end of file