Time Converting
Mix.install([
{:jason, "~> 1.4"},
{:kino, "~> 0.9", override: true},
{:youtube, github: "brooklinjazz/youtube"},
{:hidden_cell, github: "brooklinjazz/hidden_cell"}
])
Navigation
Home Report An Issue Dates And TimesItineraryTime Converting
Often we have to convert seconds, minutes, hours, and days. You’re going to create a TimeConverter
module which can handle all of this for us.
We’ll use the atoms :days
, :hours
, :minutes
, or :seconds
to represent days, hours, minutes, and seconds.
Example Solution
defmodule TimeConverter do
def to_seconds(amount, unit) do
case unit do
:seconds -> amount
:minutes -> amount * 60
:hours -> amount * 60 * 60
:days -> amount * 60 * 60 * 24
end
end
def from_seconds(amount, unit) do
case unit do
:seconds -> amount * 1.0
:minutes -> amount / 60
:hours -> amount / 60 / 60
:days -> amount / 60 / 60 / 24
end
end
end
Implement the TimeConverter.to_seconds/2
and TimeConverter.from_seconds/2
functions as documented.
defmodule TimeConverter do
@moduledoc """
Documentation for `TimeConverter`
"""
@doc """
Convert a unit of time to a number of seconds.
## Examples
iex> TimeConverter.to_seconds(1, :seconds)
1
iex> TimeConverter.to_seconds(1, :minutes)
60
iex> TimeConverter.to_seconds(1, :hours)
3600
iex> TimeConverter.to_seconds(1, :days)
86400
"""
def to_seconds(amount, unit) do
case unit do
:seconds -> amount
:minutes -> 60 * amount
:hours -> 60 * 60 * amount
:days -> 60 * 60 * 24 * amount
end
end
@doc """
Convert a number of seconds to a unit of time.
Return a float, as these values will require division using `/`.
## Examples
iex> TimeConverter.from_seconds(1, :seconds)
1.0
iex> TimeConverter.from_seconds(60, :minutes)
1.0
iex> TimeConverter.from_seconds(3600, :hours)
1.0
iex> TimeConverter.from_seconds(86400, :days)
1.0
"""
def from_seconds(amount, unit) do
case unit do
:seconds -> amount * 1.0
:minutes -> amount / 60
:hours -> amount / 60 / 60
:days -> amount / 60 / 60 / 24
end
end
end
Commit Your Progress
DockYard Academy now recommends you use the latest Release rather than forking or cloning our repository.
Run git status
to ensure there are no undesirable changes.
Then run the following in your command line from the curriculum
folder to commit your progress.
$ git add .
$ git commit -m "finish Time Converting exercise"
$ git push
We’re proud to offer our open-source curriculum free of charge for anyone to learn from at their own pace.
We also offer a paid course where you can learn from an instructor alongside a cohort of your peers. We will accept applications for the June-August 2023 cohort soon.