I am using datefns to work with dates and I have the following date:
'05 okt 2022'
How can I convert this to a date object in javascript?
I have tried the following:
import { parse } from 'date-fns'
import {nl} from 'date-fns/locale';
parse('05 okt 2022', "dd MMM yyyy", new Date(), { locale: nl})
However this gives an invalid date.
It is not very convenient to use multiple libraries when working with dates, as usually each library has its own date pattern and format/parse rules. Seems that you want to use date-fns
just to parse the date string generated by litepie
, which is a bit overkill considering that it weights 26.8
kB minified+gzipped.
That parsing can be implemented in a few lines of code:
// build the months names list, MMM
const months = new Map([...Array(12)]
.map((x, i) => [new Date(2022, i, 1, 0, 0, 0, 0)
.toLocaleDateString('nl-NL', {month: 'short'}).slice(0, 3), i]));
const parse = date => {
const i = date.split(' ');
return new Date(i[2], months.get(i[1].slice(0, 3)), i[0]);
};
console.log(parse('05 okt 2022').toString());
console.log(parse('08 mrt 2022').toString());