6

I'm experimenting with dayjs. Following the example in the documentation, I have set this in my HTML script:

<script src="https://unpkg.com/dayjs@1.10.4/dayjs.min.js"></script>
<script src="https://unpkg.com/dayjs@1.10.4/locale/en-gb.js"></script>

In my JS code, I have the lines:

var locale = dayjs.locale('en-gb');
var date = dayjs('1/4/21').format('DD MMM YYYY');

The first line correctly returns locale as 'en-gb'. However, the second line returns date as '04 Jan 2021' when it should be '01 Apr 2021', according to the standard British English date order of DMY.

I have checked that the en-gb locale file has the date the right way round.

How do I correct this issue?

Edit

I've since found that moment has the same problem when using moment-with-locales.js.

magnol
  • 344
  • 3
  • 15

2 Answers2

3

This might not answer the question, in that you were asking specifically how tot parse dates using the local feature. But I got around it using the custom parse plugin:

const customParseFormat = require("dayjs/plugin/customParseFormat");
dayjs.extend(customParseFormat);
dayjs("01/04/2021", "DD/MM/YYYY").format("DD MMM YYYY")
Rusty
  • 609
  • 1
  • 4
  • 19
0

As mentioned by the OP, this functionality isn't supported by the dayjs or momentjs at the time of writing this question.

Here's an ES6 solution to the problem:

// Create this utility function
function formatLocale(dateStr: string) {
  const values = dateStr.split('/');

  // Make sure string is valid
  const isValid = values.length === 3 && values.every(val => val.length > 0);
  if (!isValid) return dateStr; // don't change if date isn't valid (handle error however you want)

  if (dayjs.locale() === 'en-gb')
    return `${values[1]}/${values[0]}/${values[2]}`;
  // otherwise
  return dateStr;
}

// Usage
dayjs(formatLocale('1/4/2022')).format('DD MMM YYYY') // "01 April 2022"

Create a utility function formatLocale which can be used to to check the current locale of dayjs, if it is "en-gb" it will manipulate the string input appropriately to match what is expected by dayjs. If the locale is anything else OR if the string input is invalid then it won't manipulate the input string.

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143