javascriptreactjsmomentjs

moment locale when you using fromNow()


We are using the function fromNow() of moment, but I noticed that this function isn't able to localize his results.

These are my imports:

    <SettedWrapper>
      <CueBall size={24} margin="0 10px 0 0" status={status} />
      <div>
        <StatusLabel status={status}>
          <FormattedMessage {...messageStatus} />
        </StatusLabel>
        {console.log(
          'sei qua ---------------------->',
          moment(date)
        .locale(moment.locale('it-IT'))
        .fromNow(),
        )}
        <GrayLabel>
          {moment(date)
            .locale(moment.locale('it-IT'))
            .fromNow()}
        </GrayLabel>
      </div>
    </SettedWrapper>

As result of console log I will have this: consoleLogResults

How can I localize the results of the function fromNow()? It's the only part of the site that isn't localized.


Update

I found this https://github.com/moment/moment/issues/2042, that is related to this bug if can help you.


Solution

  • You have to simply pass the locale identifier to locale(String) function, so you should use:

    moment(date).locale('it').fromNow()
    

    instead of

    moment(date).locale(moment.locale('it-IT')).fromNow()
    

    Moreover, make sure you have properly loaded the required locale (see Loading locales in NodeJS, Loading locales in the browser and Where to use it section of the documentation)

    Example:

    const date = "2020-04-01";
    console.log( moment(date).fromNow() );
    console.log( moment(date).locale('it').fromNow() );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>