Search code examples
rubydate-conversion

Ruby: how to convert VARIANT DATE to datetime


In my project i get from external system date&time in VARIANT DATE type and need to convert it to datetime (i.e. 43347.6625 => 04/09/2018 16:29:59).

Do you know how to do it in ruby? what is the best approach? I did not find any ruby built-in method to do such a conversion...


Solution

  • here a method to do the calculation, the date you give is not correct, it should be what this method is returning, check with https://planetcalc.com/7027/

    def variant2datetime variant
      # number of days after 1-1-1900 minus 2 days for starting with 0
      # and having a day that didn't exist because 1900 wasn't a leap year
      date = Time.new("1900-01-01") + (variant.to_i - 2) * 24 * 60 * 60
      fraction = variant % 1
      hours   = (fraction - fraction.to_i) * 24
      minutes = (hours - hours.to_i) * 60
      seconds = (minutes - minutes.to_i) * 60
      Time.new(date.year, date.month, date.day, hours.to_i, minutes.to_i, seconds.to_i)
    end
    
    variant2datetime 43347.6625 # 2018-09-04 15:53:59 +0200