Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment: format using other locale without changing global moment locale

I have a requirement where I need to format some specific moment objects under a given locale, even if moment.locale() is set to something else. Is it possible to somehow invoke format in such a way that it uses the static locale only for the current operation?

I know that I can do something like:

let oldLocale = moment.locale();
moment.locale('theStaticLocale');
let formattedDate = moment.format('asdasd');
moment.locale(oldLocale);

However, this feels completely wrong. What I want instead is something akin to:

let formattedDate = moment.format('asdasd','theStaticLocale');
like image 291
csvan Avatar asked Sep 11 '25 14:09

csvan


2 Answers

From moment docs - Changing locales locally

var aa = moment();

aa.locale('fr');
aa.format('LLLL');

aa.locale('en');
aa.format('LLLL');
like image 72
elpddev Avatar answered Sep 14 '25 03:09

elpddev


Setting global locale:

moment.locale('en');

Setting a moment object that’ll use global locale:

let g = moment();

Setting a moment object that’ll use another locale:

let x = moment();
x.locale('fr');

Printing:

console.log(g.format('LLLL')); // Sunday, July 15 2012 11:01 AM
console.log(x.format('LLLL')); // dimanche 15 juillet 2012 11:01
like image 24
gsc Avatar answered Sep 14 '25 03:09

gsc