节点中的日期toLocaleDateString

evf*_*qcg 11 javascript node.js

当我toLocaleDateString在浏览器中使用它返回

n = new Date()
n.toLocaleDateString()
"2/10/2013"
Run Code Online (Sandbox Code Playgroud)

但在node.js格式完全不同

n = new Date()
> n.toLocaleDateString()
'Sunday, February 10, 2013'
Run Code Online (Sandbox Code Playgroud)

如何mm/dd/yy在node.js中获取浏览器的格式()?

Rnd*_*max 14

对我来说,解决方案是full-icufull-icu-npm安装一个额外的模块node js

在package.json之后插入:

{"scripts":{"start":"node --icu-data-dir=node_modules/full-icu YOURAPP.js"}}
Run Code Online (Sandbox Code Playgroud)

要么

在当前版本的Node.js v10.9.0中是Internationalization Support.要控制在Node.js中如何使用ICU,您可以配置编译期间可用的选项.如果使用该small-icu选项,则需要在运行时提供ICU数据:

  • 在  NODE_ICU_DATA  环境变量:?env NODE_ICU_DATA=/some/directory node
  • 所述  --icu数据-DIR  CLI参数:
 node --icu-data-dir=/some/directory?


Mar*_*hal 6

我也在node.JS中发现了这个问题。例如,在节点控制台中,键入

new Date().toLocaleDateString('en-GB')
Run Code Online (Sandbox Code Playgroud)

它仍然显示美国格式。使用上述Werner的方法,您可以覆盖区域设置的默认Date.toLocaleDateString()行为:

Date.prototype.toLocaleDateString = function () {
    return `${this.getDate()}/${this.getMonth() + 1}/${this.getFullYear()}`;
};
Run Code Online (Sandbox Code Playgroud)


Wer*_*rås -19

Date.prototype.toLocaleDateString = function () {
  var d = new Date();
  return (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
};
Run Code Online (Sandbox Code Playgroud)

  • 如果您唯一的解决方案是覆盖原型,那么您可能应该只编写自定义格式转换方法。 (15认同)