Cain Nuke
Cain Nuke

Reputation: 3079

toLocaleString not getting the language I set on node.js

Im on node.js editing a server side file and I want to get the date in mexican spanish format like this:

const bdate = new Date(1980, 4-1, 3);
const birthdate = bdate.toLocaleString('es-MX', { month: 'short', year : 'numeric', day : 'numeric' });
console.log(birthdate);

but this produces Apr 3, 1980 whereas it should be: 3-abr-1980

This code works fine on a client side file but not here. What is wrong here?

Thanks.

Upvotes: 1

Views: 419

Answers (1)

Pietro Nadalini
Pietro Nadalini

Reputation: 1800

You can achieve the date format you want with just "es" language instead of "es-MX" and then just substitute the spaces for -. Another solution would be based on this answer, you can achieve the same result with Intl.DateTimeFormat

I provided some examples here:

const bdate = new Date(1980, 4-1, 3);
const birthdate = bdate.toLocaleString('es', { month: 'short', year : 'numeric', day : 'numeric' }).replaceAll(" ", "-");

console.log(birthdate)


function join(t, a, s) {
   function format(m) {
      let f = new Intl.DateTimeFormat('es', m);
      return f.format(t);
   }
   return a.map(format).join(s);
}


let a = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}];
let s = join(bdate, a, '-');
console.log(s);

let ye = new Intl.DateTimeFormat('es', { year: 'numeric' }).format(bdate);
let mo = new Intl.DateTimeFormat('es', { month: 'short' }).format(bdate);
let da = new Intl.DateTimeFormat('es', { day: 'numeric' }).format(bdate);
console.log(`${da}-${mo}-${ye}`);

Upvotes: 1

Related Questions