DCSIMG
JavaScript Date localization problems - Pini Dayan

Pini Dayan

The best thing about a boolean is even if you are wrong, you are only off by a bit.

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.

Comments

Jerry spenser said:

Hi Pini, as usual great post.

It is a nicfe solution to this annoying problem.

# May 5, 2009 10:46 AM

מאיר said:

היי פיני, תודה על הפוסט המצוין, בדיוק לפני כמה ימים חיפשתי את המידע הזה ונתקלתי בלא מעט שטויות.

# May 5, 2009 10:47 AM

Jessice J said:

Very nice. thanks

# May 5, 2009 10:48 AM

Avi Pinto said:

a better way is always sending the client dates where the month is represented by letters

like: "15 feb 2009"

then var test=new Date("28 feb 2009") will be a valid date just like you want it

# May 6, 2009 12:20 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: