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

Asked

Viewed 168 times

-2

I want to take the value of a date string formatted as MMM/yyyy for the format yyyy-MM.

For example, for abr/2017, want to return 2017-04.

I wrote the following code with the library date-fns, but it’s not working:

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

format(new Date('abr/2017'),'yyyy-MM', { locale: ptBR })
  • Doesn’t the first argument of format() have to be a date instead of a string? Maybe with the toDate function()?

  • I fixed it there... That’s the code I’m trying to run, @epx

1 answer

1


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).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.