Few things are more frustrating that localizing dates in JS, but it’s doable.
It’s doable, though. It doesn’t take a lot of work, but it can take quite a bit of time to wade through all of the information and find an appropriate solution. So, the first thing we need to do is get the user’s current locale, right? This one is pretty easy to do with the following:
var browserLocale = window.navigator.userLanguage || window.navigator.language;
Our first step is to tell Moment.js which locale we wish to use. This is easy enough, as we already have the user’s locale in the browserLocale variable:
Next we need to get all of the information about this locale’s specific settings, which moment provides as a locale object:
var theLocale = moment.localeData();
If you inspect theLocale, you can see all of the wonderful information that Moment.js is giving us access to (or you could hit up the documentation, whatever floats your boat). This makes the process simple, but not as simple as a JS built-in way of doing things would have made it.
Now, all we need to do to get the date format is pull it from our theLocale variable:
var shortFormat = theLocale.longDateFormat('L');
And that’s it. shortFormat will now contain the format string for short dates. For me, this is “MM/DD/YYYY”.
So, let’s say that you need to format a Date object to string using shortFormat. We need to first create a moment from the JS Date object:
var theMoment = new moment(value);
Then we’ll grab the formatted value:
var formattedDate = theMoment.format(shortFormat);
Now, formattedDate will contain the formatted date string, which in my case is “05/17/2017” as of this writing. I’ve also created a small JSFiddle for this so that you can easily play around with it and see how robust this solution is.