dayjs does not parse British English dates correctly
Asked Answered
V

3

7

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

<script src="https://unpkg.com/[email protected]/dayjs.min.js"></script>
<script src="https://unpkg.com/[email protected]/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.

Vinson answered 7/2, 2021 at 15:3 Comment(0)
M
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")
Misspell answered 6/7, 2021 at 18:1 Comment(1)
See, I'd like this to work, but I also want it to ingest EVERY en-GB or european style format. DD-MM-YYYY, DD.MM.YY, etc. It gives you this flexibility with US format, why not en-GB?Nonanonage
C
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.

Chinua answered 20/1, 2022 at 9:40 Comment(0)
B
0

You need to import the specific locale from dayjs.

import 'dayjs/locale/en-gb';

https://day.js.org/docs/en/i18n/i18n

Banter answered 25/3, 2024 at 16:50 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.