【问题标题】:toLocaleString not getting the language I set on node.jstoLocaleString 没有得到我在 node.js 上设置的语言
【发布时间】:2021-09-22 04:07:19
【问题描述】:

我在 node.js 上编辑服务器端文件,我想以墨西哥西班牙语格式获取日期,如下所示:

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

但这会产生Apr 3, 1980,而它应该是:3-abr-1980

此代码在客户端文件上运行良好,但在此处不行。这里有什么问题?

谢谢。

【问题讨论】:

  • 我在 Firefox 上,但我在 chrome 上也有同样的问题。
  • 在 sn-p 上它可以工作。也许是因为我在 node.js 服务器端?
  • 似乎是,node.js 是罪魁祸首。我关闭了这个问题并打开了一个新问题。
  • 这能回答你的问题吗? Using .toLocaleString() in Node.js
  • 我确实看过,但它很旧。也许那里有新的替代品?

标签: javascript node.js date locale


【解决方案1】:

您可以使用"es" 语言而不是“es-MX”来实现您想要的日期格式,然后只需将空格替换为-。另一种解决方案是基于this answer,您可以使用Intl.DateTimeFormat获得相同的结果

我在这里提供了一些例子:

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}`);

【讨论】:

  • 感谢您的努力,但没有更短的方法吗?
  • 第一个选项只是添加一个replaceAll,这是我能找到的最短版本,否则您需要添加另一个可以更轻松地处理命运格式的包
猜你喜欢
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
相关资源
最近更新 更多