jsmreese / moment-duration-format

Format function plugin for the Moment Duration object.
MIT License
967 stars 121 forks source link

locale formatting does not work with locally set locale #112

Open timbowhite opened 6 years ago

timbowhite commented 6 years ago

moment.js has 2 ways to set the locale: globally (all moment instances will use the set locale) or locally (only the single moment object instance will use the set locale).

moment-duration-format only seems to work when the locale is set globally. Below is an example where moment-duration-format uses the global locale even when the locale has been changed locally:

var moment = require('moment');
var momentDurationFormatSetup = require("moment-duration-format");

momentDurationFormatSetup(moment);

moment.updateLocale('es', {
    durationLabelsStandard: {
        "S": "milisegundo",
        "SS": "milisegundos",
        "s": "segundo",
        "ss": "segundos",
        "m": "minuto",
        "mm": "minutos",
        "h": "hora",
        "hh": "horas",
        "d": "día",
        "dd": "días",
        "w": "semana",
        "ww": "semanas",
        "M": "mes",
        "MM": "meses",
        "y": "año",
        "yy": "años"
    },
    months : [
        "foo", "foo", "foo", "foo", "foo", "foo",
        "foo", "foo", "foo", "foo", "foo", "foo"
    ]
});

moment.locale('es');

// locale is set globally to es, correctly outputs '60 segundos'
console.log(moment.duration(60, 's').format('s __'));

moment.locale('en');

// locale is set locally to es, correctly outputs 'foo'
console.log(moment().locale('es').format('MMMM'));

// bug: locale is set locally to es, outputs '60 seconds', should output '60 segundos'
console.log(moment.duration(60, 's').locale('es').format('s __'));

moment: 2.22.1 moment-duration-format: 2.2.2

jsmreese commented 6 years ago

Thanks for logging this issue.

Definitely something that should get fixed. Hopefully I can make some time for this project again this summer.

muratonnet commented 4 years ago

great point @timbowhite here is the fix i think;

change line 891 from

890        // Cache moment's locale data.
891        var localeData = moment.localeData();

to

890        // Cache moment's locale data.
891        var localeData = this.localeData();
moment.duration(3973274078).locale('es').format();
// 1 mes, 16 días

ole :)