Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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." : ""
        }`
    );
like image 523
aolivera Avatar asked Aug 21 '20 15:08

aolivera


People also ask

Should I use moment or Luxon?

Moment. js is much nicer than native Dates, but there's still room for improvement. Luxon is a modern Javascript date/time library built by one of the Moment. js developers to address some shortcomings in the old standby for date manipulation.

What IS luxon?

Luxon is a library for working with dates and times in JavaScript.

What is fromJSDate?

▸ fromJSDate(date, options) Create a DateTime from a JavaScript Date object. Uses the default zone.


1 Answers

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>
like image 91
Alexandr Tovmach Avatar answered Sep 16 '22 14:09

Alexandr Tovmach