javascriptluxon

Luxon toRelative alternative wording


When using Luxon's toRelative, is there a way to tell the function to output e.g. 3 months old instead of 3 months ago? Or is there another method in the library? Or do I need to manually build the string?


Solution

  • The usage of "ago" in the English locale is not customizable. You can see that it is a static string suffix by tracing the call stack in the source code from the toRelative method to the final return statement of the formatRelativeTime function:

    return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`;
    

    Because of this, you can use a conditional string replacement approach as shown in the function toRelativeCustom below to achieve your objective.

    Note that Luxon's API does not specify the format of the relative date strings for any locales, so breaking changes are possible in the future.

    <script type="module">
    
    import { DateTime } from "https://cdn.jsdelivr.net/npm/luxon@3.4.3/build/es6/luxon.js";
    
    function toRelativeCustom(dt) {
      const str = dt.toRelative();
      return str.endsWith(" ago") ? `${str.slice(0, -4)} old` : str;
    }
    
    const dt = DateTime.now().minus({ months: 3 });
    
    console.log(dt.toRelative()); // "3 months ago"
    console.log(toRelativeCustom(dt)); // "3 months old"
    
    </script>