Packages

A lightweight Gleam library for formatting timestamps as human-readable relative time strings (e.g., '5 minutes ago', 'in 2 hours') with support for multiple locales.

Current section

Files

Jump to
timeago src timeago.erl
Raw

src/timeago.erl

-module(timeago).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).
-define(FILEPATH, "src/timeago.gleam").
-export([time_ago/3]).
-file("src/timeago.gleam", 6).
-spec time_ago(
gleam@time@timestamp:timestamp(),
gleam@option:option(gleam@time@timestamp:timestamp()),
gleam@option:option(binary())
) -> binary().
time_ago(Timestamp, Maybe_now, _) ->
Now = gleam@option:unwrap(Maybe_now, gleam@time@timestamp:system_time()),
{Seconds, Nanoseconds} = gleam@time@duration:to_seconds_and_nanoseconds(
gleam@time@timestamp:difference(Timestamp, Now)
),
Diff = case (Seconds < 0) andalso (Nanoseconds > 0) of
true ->
Seconds + 1;
false ->
Seconds
end,
case Diff of
0 ->
<<"just now"/utf8>>;
_ ->
Diff_magnitude = gleam@int:absolute_value(Diff),
{Amount, Unit} = case Diff_magnitude of
N when N < 60 ->
{N, <<"second"/utf8>>};
N@1 when N@1 < 3600 ->
{N@1 div 60, <<"minute"/utf8>>};
N@2 when N@2 < 86400 ->
{N@2 div 3600, <<"hour"/utf8>>};
N@3 when N@3 < 2635200 ->
{N@3 div 86400, <<"day"/utf8>>};
N@4 when N@4 < 31536000 ->
{N@4 div 2635200, <<"month"/utf8>>};
N@5 ->
{N@5 div 31536000, <<"year"/utf8>>}
end,
Unit_suffix = case Amount of
1 ->
<<""/utf8>>;
_ ->
<<"s"/utf8>>
end,
case Diff < 0 of
true ->
<<<<<<<<"in "/utf8,
(erlang:integer_to_binary(Amount))/binary>>/binary,
" "/utf8>>/binary,
Unit/binary>>/binary,
Unit_suffix/binary>>;
false ->
<<<<<<<<(erlang:integer_to_binary(Amount))/binary,
" "/utf8>>/binary,
Unit/binary>>/binary,
Unit_suffix/binary>>/binary,
" ago"/utf8>>
end
end.