Search code examples
ruby-on-railsrubyhexunix-timestamp

Convert unix hex timestamp to ruby datetime


i have hex timestamp like this '6132103D' (got it from facebook API) according to this service i get expected date Friday, September 3, 2021 12:08:29 PM. I have seen such discussion but there is no any success

Cannot use Time.at because i operate with String.

Be thankful if you suggest some solution or gem which i could use.

ruby 2.7.1 rails 6.0.3.2


Solution

  • First you need to convert hex value to decimal.

    Then, use Time.at() or DateTime.strptime() function to get the timestamp

    2.5.3 :019 > DateTime.strptime(str.to_i(16).to_s, '%s')
     => Fri, 03 Sep 2021 12:08:29 +0000 
    
    2.5.3 :020 > Time.at(str.to_i(16))
     => 2021-09-03 17:38:29 +0530 
    

    Crossverified using https://www.epochconverter.com/hex

    hex timestamp : 6132103D
    

    Equivalent timestamp:

    GMT: Friday, September 3, 2021 12:08:29 PM
    Your time zone: Friday, September 3, 2021 5:38:29 PM GMT+05:30
    Decimal timestamp/epoch: 1630670909