19

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?

evfwcqcg
  • 15,755
  • 15
  • 55
  • 72

4 Answers4

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

Rndmax
  • 220
  • 2
  • 8
  • I feel like it is only answer. Is it possible to make configure node globally to find `full-icu` from global modules? – Marecky Aug 23 '18 at 23:07
  • 1
    @Marecky Of course. Method same. In the example there is a module installation globally `npm install -g full-icu` – Rndmax Aug 25 '18 at 06:54
12

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.

Marshal
  • 4,452
  • 1
  • 23
  • 15
-6

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.

Anand
  • 4,523
  • 10
  • 47
  • 72
  • That doesn't preclude the server from specifying a default (just as it does with timezones) or from allowing you to specify a locale (the first parameter of `toLocaleDateString`). – mattbasta May 28 '14 at 20:11
  • 8
    It doesn't seem to work at all on my server (Node 0.10.28). Whatever value I give to `toLocaleDateString`, it still ouputs in American English format... – Waldo Jeffers Jul 22 '14 at 14:14
-19
Date.prototype.toLocaleDateString = function () {
  var d = new Date();
  return (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
};
Werner Kvalem Vesterås
  • 10,226
  • 5
  • 43
  • 50
  • 15
    If your only solution is to overwrite the prototype, you should probably just write a custom format translation method instead. – jennz0r May 26 '17 at 01:04