Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save moreta/7e2d3cc275cf552791b3 to your computer and use it in GitHub Desktop.
Save moreta/7e2d3cc275cf552791b3 to your computer and use it in GitHub Desktop.
Convert seconds into HH:MM:SS or date format in Ruby
# seconds
t = 236
Time.at(t).utc.strftime("%H:%M:%S")
=> "00:03:56"
# unix time
t = 1450236594
Time.at(t).utc.strftime("%Y/%d/%d %H:%M:%S")
=> "03:29:54"
# with timezone
class Time
def timezone(timezone = 'UTC')
old = ENV['TZ']
utc = self.dup.utc
ENV['TZ'] = timezone
output = utc.localtime
ENV['TZ'] = old
output
end
end
Time.at(1450236594).timezone('Asia/Tokyo').to_datetime
Time.at(1450236594).timezone('Asia/Tokyo').strftime("%Y/%d/%d %H:%M:%S")
# Reference
# http://stackoverflow.com/questions/3963930/ruby-rails-how-to-convert-seconds-to-time
# http://qiita.com/semind/items/9614ded891d6154e9a06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment