Answer the question
In order to leave comments, you need to log in
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
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
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;
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 questionAsk a Question
731 491 924 answers to any question