I’m sorry for asking my 3rd question in a week, but I’m making so much progress I’d hate to slow down now.
I have a function (in PHP, sorry) that I need to convert the behavior of to Elixir. The function comment explains the purpose and behavior quite well:
// Take a number of seconds and return a string describing the length of time
// in the most appropriate way. If we're dealing with seconds on the order of
// hours, then return hours. If we're dealing with seconds on the order of
// years, then return years. You get the idea.
// This function takes leap years into account by treating one year as one
// year plus one forth of a day.
function display_seconds($seconds) {
if ($seconds > 94672800) { // 94,672,800 seconds is 3 years.
$seconds_in_one_year = 31557600; // 31,557,600 seconds is 1 year.
return number_format($seconds / $seconds_in_one_year) . ' years';
} elseif ($seconds > 7889400) { // 7,889,400 seconds is 3 months.
$seconds_in_one_month = 2629800; // 2,629,800 seconds is 1 month.
return number_format($seconds / $seconds_in_one_month) . ' months';
} elseif ($seconds > 1814400) { // 1,814,400 seconds is 3 weeks.
$seconds_in_one_week = 604800; // 604,800 seconds is 1 week.
return number_format($seconds / $seconds_in_one_week) . ' weeks';
} elseif ($seconds > 259200) { // 259,200 seconds is 3 days.
$seconds_in_one_day = 86400; // 86,400 seconds is 1 day.
return number_format($seconds / $seconds_in_one_day) . ' days';
} elseif ($seconds > 10800) { // 10,800 seconds is 3 hours.
$seconds_in_one_hour = 3600; // 3,600 seconds is 1 hour.
return number_format($seconds / $seconds_in_one_hour) . ' hours';
} elseif ($seconds > 90) { // 90 seconds is 3 minutes.
$seconds_in_one_minute = 60; // 60 seconds is 1 minute.
return number_format($seconds / $seconds_in_one_minute) . ' minutes';
} else {
return number_format($seconds) . ' seconds';
}
}
If you followed along, you’ll see that the function takes an amount of seconds, and turns that into a human-friendly string, for example 6 weeks or 13 years. Id’ like to accomplish the same thing in Elixir. I’ve already got the number_format() part figured out. I can use Number.Delimit.number_to_delimited() for that. It’s the if/elseif/else logic and the short-circuit returns that are my main issue. No doubt there is an entirely different approach I should be taking here, I just don’t know what it is. Or maybe even this type of time/string formatting is built into the language?
I’d appreciate any help I can get. I think I could probably adapt the answer to my previous question to accomplish something like this, but I’m not confident there either…






















