Search code examples
formatmomentjsdayofweekluxon

How to convert from Moment to Luxon for two letter day of week format?


I am converting a typescript app to use Luxon instead of Moment for datetime processing and am not sure how to use Luxon's built-in features (or configurable options) to return the day of week as two letters.

Moment: moment().format('MM/dd/y') should return '04/Tu/2022'.

Luxon: DateTime.now().toFormat('MM/ccc/yyyy') but that gives me '04/Tue/2022', which does not fit the required backend data format.

Is there an options parameter I can set to specify the number of letters to return for the day of week string? Or another approach?

This is an example that I found that allows you to specify 2 digit day and month using options...

DateTime.now().toLocaleString({ day: '2-digit', month: '2-digit', year: 'numeric' }) => 05/10/2022


Solution

  • I fear that this is not possible "natively" with Luxon, Table of tokens lists only ccc (day of the week, as an abbreviate localized string), cccc (day of the week, as an unabbreviated localized string), ccccc (day of the week, as a single localized letter) that maps exactly the possible values ('narrow', 'short', 'long') of weekday key of the Intl.DateTimeFormat option object.

    Possible workaround is to use custom function and get only first two digit of day of the week.

    const DateTime = luxon.DateTime;
    
    function customFormat(dt) {
      const year = dt.year;
      const month = dt.toFormat('MM');
      const dow = dt.toFormat('ccc').substring(0, 2);
      return month + '/' + dow + '/' + year;
    }
    
    console.log(customFormat(DateTime.now()));
    console.log(customFormat(DateTime.fromISO('2022-05-11')));
    console.log(customFormat(DateTime.fromISO('2022-05-10')));
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/build/global/luxon.min.js"></script>