Luxon interval human readable
Asked Answered
F

2

16

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." : ""
        }`
    );
Fablan answered 21/8, 2020 at 15:57 Comment(0)
B
25

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/[email protected]/build/global/luxon.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/humanize-duration.min.js"></script>
Boutis answered 10/1, 2021 at 8:49 Comment(1)
how do I implement this in angular?Rodmur
E
0

With Luxon this has become a lot simpler.

  1. First we use the diff() method to get an Interval between two DateTime objects.
  2. Then we need to use the rescale() method to rescale the interval units to their largest representation. The diff() results in milliseconds, therefore if we do not do this change the result will be a string saying "x milliseconds".
  3. Finally use the toHuman() method to get a nice and readable string.

Tip: You can filter out any parts of the result like removal of seconds by simply setting the Interval's parts to 0.

const DateTime = luxon.DateTime;

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

const formatted = finish.diff(start).rescale().toHuman({ listStyle: "long" })

console.log(formatted)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/global/luxon.min.js"></script>
Encouragement answered 28/5 at 10:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.