A service I am calling is providing me dates in a json response as a Microsoft format like this:
"\/Date(1458845940000)\/"
I've been looking around for the best way to handle it and convert it to the local date time correctly in javascript.
I wish to format it for example if it's the
en-US locale "MM/DD/yyyy HH:mm:ss a" -> 3/24/2016 3:59:00 PM
en-GB locale "DD/MM/yyyy HH:mm:ss" -> 24/03/2016 15:59:00
The 1st issue is trying to convert over over the given string format to a date. I settled with using this and it seems to work but I am unsure if it is the best way to do it.
var jsDate = new Date(parseInt(jsonDate.substr(6)));
It outputs it a date object which I can use now to perform the formatting using the Internationalization API. I can then use the locale that sometimes is correct (more later) to produce a date:
var jsDate = new Date(parseInt(jsonDate.substr(6)));
var locale = window.navigator.userLanguage || window.navigator.language;
jsDate.toLocaleString(locale); //3/24/2016 3:59:00 PM or 24/03/2016, 15:59:00
The format is almost there in the output but with the extra comma, but then if I strip out the comma which is a bit hokey to do or do a reformat which would not work based on localization.
My second issue, is there a sure fire way to obtain the locale? I've try to detect it by userLanguage or language but I realized that there is also browserLanguage that is used by IE.
var locale = window.navigator.userLanguage || window.navigator.language;
The above is inconsistent and not full proof it seems because for example in chrome if you have multiple languages set in your Language and Input Settings it pulls the last one in the list when chrome defaults to the first one in the list and not sure how other browsers would handle it.
I've read other places to use momentjs which I tried by including moment.min.js and moment-with-locales.min.js. But it also did not work:
var jsDate = new Date(parseInt(jsonDate.substr(6)));
var locale = window.navigator.userLanguage || window.navigator.language;
moment.locale(locale);
var newDate = moment(jsDate).format("L LTS") //03/24/2016 3:59:00 PM but does not change base on locale so it remains MM/DD/YYYY ... even though I changed locale
I did see an issue posted in momentjs about this but it was older. https://github.com/moment/moment/issues/1044
I am unsure if I am missing something stupid or if there is a better way to do this? Thanks