javascriptluxon

Luxon interval human readable


Hi I would like to express a luxon interval in a localized human-readable manner (Eg. 9 days, 3 hours).

I have achieved this starting from present moment. With this code:

DateTime.fromISO(value).toRelative({ locale: "es" });

But I cannot achieve the same using neither the Interval o the Duration objects.

This get's the job done. But is not really localization.

    const start = DateTime.fromSQL("2020-06-19 11:14:00");
    const finish = DateTime.fromSQL("2020-06-21 13:11:00");

    const {days, hours, minutes} = Interval
        .fromDateTimes(start, finish, {locale: "es"})
        .toDuration(["days", "hours", "minutes"]).values;
    
    console.log(
        `${days ? days + " días " : ""} ${hours ? hours + " horas" : ""} ${
            minutes ? minutes + " minutos." : ""
        }`
    );

Solution

  • Duration haven't any analogues of humanize() method, so you should use a third-party library. For example, humanize-duration, with multilanguage support.

    const DateTime = luxon.DateTime;
    const Interval = luxon.Interval;
    
    const start = DateTime.fromSQL("2020-06-19 11:14:00");
    const finish = DateTime.fromSQL("2020-06-21 13:11:00");
    
    const formatted = Interval
        .fromDateTimes(start, finish)
        .toDuration()
        .valueOf();
    
    console.log(humanizeDuration(formatted))
    console.log(humanizeDuration(formatted, { language: 'es' }))
    console.log(humanizeDuration(formatted, { language: 'ru' }))
    <script src="https://cdn.jsdelivr.net/npm/luxon@1.25.0/build/global/luxon.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/humanize-duration@3.25.1/humanize-duration.min.js"></script>