Reputation: 434
I would like to replace moment
by date-fns
in one of my projects.
From moment
, I only use parse and timezone (with moment-timezone
) functionnalities:
const moment = require('moment-timezone')
const parseDatetime = function parseDatetime (datetime, format, tz = 'Europe/Paris', locale = 'fr') {
return +moment.tz(datetime, format, locale, tz)
}
parseDatetime('jeudi 23 janvier 13:18:23', 'dddd DD MMMM HH:mm:ss')
// => 1579781903000
// Which outputs « 2020-01-23T12:18:23.000Z » (as expected) when given to Date constructor
With date-fns
, I tried format
function (which seems to be what I need) :
const format = require('date-fns/format')
const fr = require('date-fns/locale/fr')
format('jeudi 23 janvier 13:18:23', 'EEEE dd MMMM HH:mm:ss', {
locale: fr
})
First, I do not know if I should use MMMM
or LLLL
for month in locale format.
Anyway, I get following error :
Starting with v2.0.0-beta.1 date-fns doesn't accept strings as arguments. Please use `parseISO` to parse strings. See: https://git.io/fjule
So I went to documentation about parseISO
, where it states that it will « Parse the given string in ISO 8601 format and return an instance of Date. ». This is NOT what I need, as my date string isn’t in ISO 8601 format or any other ISO format.
I found parse
function, which seems to better fit my use case. So I tried :
const parse = require('date-fns/parse')
const fr = require('date-fns/locale/fr')
parse('jeudi 23 janvier 13:18:23', 'EEEE dd MMMM HH:mm:ss', Date(), {
locale: fr
})
Which gives me the exact same error as format
!!! This behavior is weird, given that parse
’s documentation states that dateString
argument is… a string !
So, I’m actually lost on this issue, if ever it is an issue.
Could someone please give me some help / insights about this ?
Upvotes: 3
Views: 15891
Reputation: 3038
you are very close to it.
const ParseDate = require('date-fns/parse') // https://date-fns.org/docs/
const DateFrench = require('date-fns/locale/fr')
let stringDate = 'jeudi 23 janvier 13:18:23'
console.log(ParseDate(stringDate, 'EEEE dd MMMM HH:mm:ss', new Date(), { locale: DateFrench }))
=> 2020-01-23T12:18:23.000Z
Upvotes: 4