I
I
Ismail2020-02-12 11:52:33
ruby
Ismail, 2020-02-12 11:52:33

Converting seconds to human format?

Good time of the day.
I can't figure out how to convert seconds to:
1.month + day + hour + minute + second
2.year + month + day + hour + minute + second
The whole conversion breaks down. Here is the code:

when (2628000..31535999) # month
    month = seconds / 2628000
    days = (seconds - month * 2628000) / 86400
    hours = (seconds - month * 2628000 - days * 86400) / 3600
    minutes = (seconds - month * 2628000 - days * 86400 - hours * 3600) / 60
    seconds = (seconds - month * 2628000 - days * 86400 - hours * 3600 - minutes * 60)
    p month, days, hours, minutes, seconds
  when (31536000..1000000000000) # year
    year = seconds / 31536000
  end

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Blokhin, 2020-02-12
@TITnet

The conversion of the number of seconds into the number of seconds, minutes, hours and days can be done by the following method:

# frozen_string_literal: true

# convert seconds to formatted string by days, hours, minutes, seconds
#
# @param [Integer] seconds
# @param [String] template
# @return String
#
# @example
#   format_duration 183_845 # => 2 days 3 hours 4 minutes 5 seconds
def format_duration(seconds, template = '%<days>i days %<hours>i hours %<minutes>i minutes %<seconds>i seconds')
  result = {
    days: seconds / 86_400,
    hours: seconds / 3600 % 24,
    minutes: seconds / 60 % 60,
    seconds: seconds % 60
  }
  format(template, result)
end

puts format_duration 183_845

Note that you won't be able to get the number of months and years, since year and month are not constant values.
A month is not a single digit number of days, hours, minutes, etc.

H
hint000, 2020-02-12
@hint000

I don't know Ruby, I'll write it in C. :) The division is integer, the operator% is the remainder of the division.

minutes=seconds/60;
 hours=minutes/60;
  days=hours/24;
   months=days/30;
    years=days/365;
   months=months%12;
  days=days%30;
 hours=hours%24;
minutes=minutes%60;
seconds=seconds%60;

D
Dmitry Amelchenko, 2020-05-21
@i1677960

You can take ready-made methods from rails

ActiveSupport::Duration.build(3661).parts
=> {:hours=>1, :minutes=>1, :seconds=>1}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question