Search code examples
javascriptdatetime-formatluxon

Escaping characters in Luxon formatter


I'm trying to convert duration in seconds using Luxon using the Duration.fromMillis().toFormat().

I want it to output 1d2h for one day and two hours, but I can't escape the d and h.

Here's what I tried so far

Duration.fromMillis(3600 * 26 * 1000).toFormat('d\dh\h')
Duration.fromMillis(3600 * 26 * 1000).toFormat('d[d]h[h]') // Like MomentJS

Both doesn't work


Solution

  • As already stated by others in the comment, you can use single quotes to escape charcters in luxon, see Escaping secction of the docs:

    You may escape strings using single quotes:

    DateTime.now().toFormat("HH 'hours and' mm 'minutes'"); //=> '20 hours and 55 minutes'
    

    Here a working example:

    const Duration = luxon.Duration;
    console.log(Duration.fromMillis(3600 * 26 * 1000).toFormat("d'd'h'h'"));
    <script src="https://cdn.jsdelivr.net/npm/luxon@2.3.1/build/global/luxon.min.js"></script>