Reputation: 16264
I am trying to print out a date/time in a format that the user is comfortable with. I have:
options = { day: "numeric", year: "numeric", month: "short", time: "short", hour12: false, hour: "2-digit", minute: "2-digit" };
When the locale
is specified explictly, options
appear to be followed:
date.toLocaleString("en-US", options);
will produce:
Jun 26, 2017, 13:05
If I leave out the locale parameter:
date.toLocaleString(options);
will produce:
6/26/2017, 1:05:00 PM
What is the locale that will be used if I leave it out? As far as I know, the locale of my PC and browser used for the test is en-US.
How do I display date/time using the browser's locale without hardcoding?
var options = { day: "numeric", year: "numeric", month: "short", time: "short", hour12: false, hour: "2-digit", minute: "2-digit" };
var D = new Date();
d = D.toLocaleString("en-US", options);
e = D.toLocaleString(options);
f = D.toLocaleString("en-US");
$("#d").text(d);
$("#e").text(e);
$("#f").text(f);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='d'></div>
<div id='e'></div>
<div id='f'></div>
Upvotes: 1
Views: 2008
Reputation: 556
opts = { day: "numeric", year: "numeric", month: "short", time: "short", hour12: false, hour: "2-digit", minute: "2-digit" };
date.toLocaleString(undefined, opts);
Taken from:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
Essentially it still requires something to be passed in for that first parameter. Otherwise it ignores your options object.
Upvotes: 4