Current section
Files
Jump to
Current section
Files
src/scriptorium/utils/time.gleam
import gleam/int
import gleam/order.{type Order, Eq}
import gleam/string
import kielet.{gettext as g_}
import kielet/context.{type Context}
import scriptorium/utils/ints/hour.{type Hour}
import scriptorium/utils/ints/minute.{type Minute}
pub type Time {
Time(hours: Hour, minutes: Minute)
}
/// Compare if `a` is before (lower than) than `b`.
pub fn compare(a: Time, b: Time) -> Order {
case hour.compare(a.hours, b.hours) {
Eq -> minute.compare(a.minutes, b.minutes)
other -> other
}
}
/// Parse a time from an `hh:mm` format string.
pub fn parse(str: String) {
case string.split(str, ":") {
[hours, minutes] ->
case int.parse(hours), int.parse(minutes) {
Ok(h), Ok(m) ->
case hour.from_int(h), minute.from_int(m) {
Ok(h), Ok(m) -> Ok(Time(h, m))
_, _ -> Error(Nil)
}
_, _ -> Error(Nil)
}
_ -> Error(Nil)
}
}
/// Format a time to a string.
pub fn format(time: Time, context: Context) -> String {
let hrs = hour.to_int(time.hours)
let mins = minute.to_int(time.minutes)
let period = get_period(hrs, context)
g_(context, "{h24_0}:{min_0}")
|> string.replace("{h24_0}", pad(int.to_string(hrs)))
|> string.replace("{h24}", int.to_string(hrs))
|> string.replace("{h12_0}", pad(int.to_string(hrs % 12)))
|> string.replace("{h12}", int.to_string(hrs % 12))
|> string.replace("{min_0}", pad(int.to_string(mins)))
|> string.replace("{min}", int.to_string(mins))
|> string.replace(
"{period}",
string.slice(period, 5, string.length(period) - 5),
)
}
/// Format a time to an `hh:mm` 24 hour string.
pub fn format_iso(time: Time) {
pad(int.to_string(hour.to_int(time.hours)))
<> ":"
<> pad(int.to_string(minute.to_int(time.minutes)))
}
/// Get a time at hour 0 and minute 0.
pub fn nil_time() {
let assert Ok(h) = hour.from_int(0)
let assert Ok(m) = minute.from_int(0)
Time(h, m)
}
fn pad(part: String) {
string.pad_start(part, 2, "0")
}
fn get_period(hour: Int, context: Context) {
case hour {
0 -> g_(context, "<00> am")
1 -> g_(context, "<01> am")
2 -> g_(context, "<02> am")
3 -> g_(context, "<03> am")
4 -> g_(context, "<04> am")
5 -> g_(context, "<05> am")
6 -> g_(context, "<06> am")
7 -> g_(context, "<07> am")
8 -> g_(context, "<08> am")
9 -> g_(context, "<09> am")
10 -> g_(context, "<10> am")
11 -> g_(context, "<11> am")
12 -> g_(context, "<12> pm")
13 -> g_(context, "<13> pm")
14 -> g_(context, "<14> pm")
15 -> g_(context, "<15> pm")
16 -> g_(context, "<16> pm")
17 -> g_(context, "<17> pm")
18 -> g_(context, "<18> pm")
19 -> g_(context, "<19> pm")
20 -> g_(context, "<20> pm")
21 -> g_(context, "<21> pm")
22 -> g_(context, "<22> pm")
_ -> g_(context, "<23> pm")
}
}