Search code examples
javascriptdateformattinglocaledate-fns

How to get back a date formatted in MMM/yyyy format to yyyy-MM format with date-fns


I want to get the value of a date string formatted as MMM / yyyy for the yyyy-MM format .. for example for abr/2017 I want to return 2017-04 I wrote the following code with the date-fns library, however is not working, it is returning me 2017-01

import format from 'date-fns/format';
import ptBR from 'date-fns/locale/pt-BR';

format(new Date('abr/2017'),'yyyy-MM', { locale: ptBR })

*** Important... I want to use the locale pt-BR


Solution

  • What you need to do firstly is to parse 'abr/2017' to a Date. In the statement:

    format(new Date('abr/2017'),'yyyy-MM', { locale: ptBR })
    

    the expression new Date('abr/2017') is evaluated first, so it's parsed by the Date constructor using the host's built–in parser which almost certainly returns an invalid date. So anything after that is pretty useless.

    You need to parse the string with date-fns like:

    let date = dateFns.parse('abr/2017','MMM-yyy',new Date(), {locale:'pt-BR'});
    

    however I don't know how to tell date-fns to use Portuguese for parsing. My testing at npm.runkit wasn't able to load pt-BR.

    Once you have a Date, you can then format it using date-fns.

    PS: Unfortunately the term "locale" has been confused with "language" by ECMA-402 and the misnomer has been adopted by a number of libraries. The language code "pt-BR" represents a language, not a locale, so often the context it's being used in is unclear.

    A more appropriate use of locale is for IANA representative locations, like 'America/Sao_Paulo', however they are now misnamed "timezones" when they are actually locations that represent a historic set of UTC offset changes such as local standard time and daylight saving (and are called "representative locations" by IANA).