evfwcqcg
evfwcqcg

Reputation: 16335

Date toLocaleDateString in node

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?

Upvotes: 19

Views: 15798

Answers (4)

Marshal
Marshal

Reputation: 4860

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.

Upvotes: 12

Rndmax
Rndmax

Reputation: 220

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


Upvotes: 22

Anand
Anand

Reputation: 4551

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.

Upvotes: -6

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

Upvotes: -19

Related Questions