Search code examples
javascriptdayjs

Dayjs custom locale throws Formatting exceptions


I want to create a custom locale and use it with DayJs. and the procedure is mentioned here in docs

But, when I follow the procedure and create my own locale, I am unable to format the date after.

Here is the JSFiddle to inspect the same. https://jsfiddle.net/5o4pwbtc/

Here is the GitHub Issue for the same: https://github.com/iamkun/dayjs/issues/746

/*  like mentioned here
https://github.com/iamkun/dayjs/blob/dev/docs/en/I18n.md#installation
*/
const locale = {
  formats: {
    // abbreviated format options allowing localization
    LTS: 'h:mm:ss A',
    LT: 'h:mm A',
    L: 'MM/DD/YYYY',
    LL: 'MMMM D, YYYY',
    LLL: 'MMMM D, YYYY h:mm A',
    LLLL: 'dddd, MMMM D, YYYY h:mm A',
    // lowercase/short, optional formats for localization
    l: 'D/M/YYYY',
    ll: 'D MMM, YYYY',
    lll: 'D MMM, YYYY h:mm A',
    llll: 'ddd, MMM D, YYYY h:mm A'
  },
  relativeTime: {
    name: 'en',
    future: '%s',
    past: '%s',
    s: 'now',
    m: 'a minute ago',
    mm: '%d minutes ago',
    h: 'an hour',
    hh: '%d hours', // e.g. 2 hours, %d been replaced with 2
    d: 'a day',
    dd: '%d days',
    M: 'a month',
    MM: '%d months',
    y: 'a year',
    yy: '%d years'
  }
}

dayjs.locale(locale);

dayjs(1575872723701).format() 
// Uncaught TypeError: Cannot read property '10' of undefined
<script src="https://unpkg.com/dayjs@1.8.17/dayjs.min.js"></script>


Solution

  • You need to import all the documents mentioned on https://unpkg.com/browse/dayjs@1.8.17/, temporarily, looking at the script the locale object was missing few properties like monthsShort (idea take from en.js under locale):

    const locale = {
      formats: {
        ...
        monthsShort: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
        months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
        weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
        weekdaysShort: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_')
     }
    };