JavaScript Date localization problems
Sometimes we have to compare dates, sort some table according to some column containing grid in the client side. This brings us to try and compare dates. The problem arises when we get a solution but then fining out that if the regional settings in our machine will change the problem arises again. There are many solutions to solve these problems on the net and you can find them out when looking for "JavaScript datediff" in Google. Today I decided to find a nicer and more elegant solution , so here it is:
Let's say you have a string contains a date such as "05/04/2008". If we try to use the "constructor function" of the Date object in JavaScript like:
var oDate = new Date(sDate);
We will notice that whenever we change the regional setting to some other culture, the date object will be different. This is because this string can be read as "dd/MM/YYYY" or as "MM/dd/YYYY". (Depending on the culture)
So , here is a nice and simple way to initialize a date object correctly:
function GetDateByStringUnLocalized(sDateStr) {
var oDate = new Date();
//Parse the date according to your string
var oDateARR = sDateStr.split("/");
oDate.setDate(oDateARR[0]);
oDate.setMonth(oDateARR[1]);
oDate.setFullYear(oDateARR[2]);
return oDate;
}This assumes you as a programmer knows how you constructed the date string.