We have a date formatting function that seems to be producing different dates depending on browser. The function has two steps, first to determine the user's date format, the second to format the date accordingly.
// determine date string format for PrettyDate functions
var dtstr;
var dtsep;
let customDate = new Date(2222, 11, 18);
let strDate = customDate.toLocaleDateString();
let daTyp = strDate.substring(0, 2);
if (daTyp === '22') {
dtstr = 'YMD';
dtsep = ',';
}
else if (daTyp === '12') {
dtstr = 'MDY';
dtsep = ';';
}
else {
dtstr = 'DMY';
dtsep = ',';
}
// make dates human readable
function prettyDate(datestr, use) {
var date = new Date(datestr);
if (!isNaN(date.getTime())) {
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const monthCount = date.getMonth();
const theMonth = monthNames[monthCount];
const theYear = date.getFullYear();
const theDay = date.getDate();
if (use === 'short') {
if (dtstr === 'MDY') {
return theMonth + ' ' + theDay;
}
else {
return theDay + ' ' + theMonth;
}
}
else {
if (dtstr === 'YMD') {
return datestr;
}
else if (dtstr === 'MDY') {
return theMonth + ' ' + theDay + ', ' + theYear;
}
else {
return theDay + ' ' + theMonth + ' ' + theYear;
}
}
}
}
The datestr
being converted is of the format 2022-08-17 and the use
value is either 'short' or 'long'.
All the checks we have done on computers we have access to show the end date as 17 Aug 2022 or Aug 17 2022. But we have had several website users report they are getting 16 Aug 2022 or Aug 16 2022.
UPDATE
Have tried some experiments with computer timezone and there does seem to a be an affect. So the new pressing question is how do we modify the code to prevent the OS timezone from affecting the result?
Further experimenting with computer timezone setting has shown that if the timezone is UTC +XX:00, then the date displayed is correct. If it is UTC -XX:00, then the date is one day earlier.
FINALLY
I officially award myself the Dunderhead Award of the day. My datestr
is basically a string, so just use split()
and reform the parts. What a over-engineered noob move.
function prettyDate(datestr, use) {
const dtparts = String(datestr).split('-');
const monthNames = ["","Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const monthCount = +dtparts[1];
const theMonth = monthNames[monthCount];
const theYear = dtparts[0];
const theDay = dtparts[2];
... previous code
}
Thanks to those who tried to help.