最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Date toLocaleDateString in node - Stack Overflow

programmeradmin2浏览0评论

When I use toLocaleDateString in browser it returns

n = new Date()
n.toLocaleDateString()
"2/10/2013"

but in node.js the format is completely different

n = new Date()
> n.toLocaleDateString()
'Sunday, February 10, 2013'

How to get the browser's format (mm/dd/yy) in node.js?

When I use toLocaleDateString in browser it returns

n = new Date()
n.toLocaleDateString()
"2/10/2013"

but in node.js the format is completely different

n = new Date()
> n.toLocaleDateString()
'Sunday, February 10, 2013'

How to get the browser's format (mm/dd/yy) in node.js?

Share Improve this question asked Feb 9, 2013 at 23:46 evfwcqcgevfwcqcg 16.3k15 gold badges57 silver badges72 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 22

For me, the solution was to install an additional module full-icu for node js full-icu-npm

And after in package.json insert:

{"scripts":{"start":"node --icu-data-dir=node_modules/full-icu YOURAPP.js"}}

or

In the current version of Node.js v10.9.0 is Internationalization Support. To control how ICU is used in Node.js, you can configure options are available during compilation. If the small-icu option is used you need to provide ICU data at runtime:

  • the NODE_ICU_DATA environment variable: 
env NODE_ICU_DATA=/some/directory node
  • the --icu-data-dir CLI parameter:
 node --icu-data-dir=/some/directory


I also found this broken in node.JS. For example, in node console, type

new Date().toLocaleDateString('en-GB')

it still displays US format. Using Werner's method above, you can override default Date.toLocaleDateString() behavior for your locale:

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

UPDATE: 2021-12-01 Starting with Node.js v13.0.0, releases are now built with default full-icu support. So this shouldn't be a problem with later releases.

in node.JS you can not get browser's format. Node.JS runs on Server-side.

You have to do date formatting before displaying it in browser at your client side JS framework.

Date.prototype.toLocaleDateString = function () {
  var d = new Date();
  return (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
};
发布评论

评论列表(0)

  1. 暂无评论