18

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?

4

4 回答 4

20
于 2017-12-14T07:57:05.793 回答
10

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.

于 2017-03-15T00:47:34.067 回答
-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.

于 2013-05-06T06:16:37.300 回答
-20
Date.prototype.toLocaleDateString = function () {
  var d = new Date();
  return (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
};
于 2013-02-10T00:32:37.183 回答