ryan-haskell / date-format / DateFormat.Relative

A reliable way to get a pretty message for the relative time difference between two dates.

Getting relative time for two dates

relativeTime : Time.Posix -> Time.Posix -> String

This function takes in two times and returns the relative difference!

Here are a few examples to help:

relativeTime now tenSecondsAgo == "just now"

relativeTime now tenSecondsFromNow == "in a few seconds"

relativeTime now fortyThreeMinutesAgo == "43 minutes ago"

relativeTime now oneHundredDaysAgo == "100 days ago"

relativeTime now oneHundredDaysFromNow == "in 100 days"


-- Order matters!
relativeTime now tenSecondsAgo == "just now"

relativeTime tenSecondsAgo now == "in a few seconds"

relativeTimeWithOptions : RelativeTimeOptions -> Time.Posix -> Time.Posix -> String

Maybe relativeTime is too lame. (Or maybe you speak a different language than English!)

With relativeTimeWithOptions, you can provide your own custom messages for each time range.

(That's what relativeTime uses under the hood!)

You can provide a set of your own custom options, and use relativeTimeWithOptions instead.


type alias RelativeTimeOptions =
{ someSecondsAgo : Basics.Int -> String
, someMinutesAgo : Basics.Int -> String
, someHoursAgo : Basics.Int -> String
, someDaysAgo : Basics.Int -> String
, someMonthsAgo : Basics.Int -> String
, someYearsAgo : Basics.Int -> String
, rightNow : String
, inSomeSeconds : Basics.Int -> String
, inSomeMinutes : Basics.Int -> String
, inSomeHours : Basics.Int -> String
, inSomeDays : Basics.Int -> String
, inSomeMonths : Basics.Int -> String
, inSomeYears : Basics.Int -> String 
}

Options for configuring your own relative message formats!

For example, here is how someSecondsAgo is implemented by default:

defaultSomeSecondsAgo : Int -> String
defaultSomeSecondsAgo seconds =
    if seconds < 30 then
        "just now"

    else
        toString seconds ++ " seconds ago"

And here is how inSomeHours might look:

defaultInSomeHours : Int -> String
defaultInSomeHours hours =
    if hours < 2 then
        "in an hour"

    else
        "in " ++ toString hours ++ " hours"

defaultRelativeOptions : RelativeTimeOptions

If there is something you'd like to tweak based off of the defaults, this record might be a good starting point!