First of all, new Date('abr/2017')
doesn’t work the way you expect:
// cada browser dá um resultado (Chrome: 01/01/2017 - Firefox: null/invalid date)
console.log(new Date('abr/2017'));
Testing on Node and Chrome, the result was a date on January 1, 2017, but Firefox gave "invalid date".
That’s because the builder of Date
does not accept any string in any format. Only the formats specified in the specification are guaranteed to work in all browsers/environments. Any other format is dependent on the implementation and there is no guarantee that it works (about this and more, read more here, here, here, here, here and here).
Anyway, if you have the string "abr/2017" and want to convert it to another format, then first you need to convert this string to a date (ie make a Parsing) and then convert this date to the other format (ie make a formatting). I mean, you’ll also need the function parse
:
import format from 'date-fns/format';
import ptBR from 'date-fns/locale/pt-BR';
import parse from 'date-fns/parse';
// converter "abr/2017" para data
var data = parse('abr/2017', 'MMM/yyyy', new Date(), { locale: ptBR });
// converte a data para o outro formato
console.log(format(data, 'yyyy-MM', { locale: ptBR })); // 2017-04
Note that in the parse
i need to inform the format the string is in (in case, MMM/yyyy
), so that it interprets correctly. In the third argument I passed new Date()
, that he uses as a reference to fill in the remaining fields (because the string is only month and year, then he needs to know what to put in the other fields - in this case it doesn’t make much difference because I’m only using the date to format the same fields). And finally, I inform you locale so that he can correctly interpret the name of the month.
Already in the formatting, as I’m only putting the numerical values, nor needed the locale (could just be format(data, 'yyyy-MM')
that would be enough).
Doesn’t the first argument of format() have to be a date instead of a string? Maybe with the toDate function()?
– epx
I fixed it there... That’s the code I’m trying to run, @epx
– lucasbbs