JavaScript Dates in Other Countries

L

Laser Lips

Hi, I've got a script, which works with dates.
It compares two dates using an operand to test weather the first date
is '<', '>' or '=' to the second date.
Here it is.

function CompareTwoDates(firstDate,secondDate,operator)
{
var tmp;
// ConparisonType eg. <,>,= etc
// first find out if either date is a datetime stamp
if (firstDate.indexOf(":")!=-1)
{
// we assume there is a time portion to remove
tmp=firstDate.split(" ");
firstDate=tmp[0]+" "+tmp[1]+" "+tmp[2]
}
if (secondDate.indexOf(":")!=-1)
{
// we assume there is a time portion to remove
tmp=secondDate.split(" ");
secondDate=tmp[0]+" "+tmp[1]+" "+tmp[2]
}
var fdate=Date.parse(firstDate);
var sdate=Date.parse(secondDate);
var ret=false;

if (isNaN(fdate)) return "Error. First argument is not a Date";
if (isNaN(sdate)) return "Error. Second argument is not a Date";

eval("if (fdate"+operator+"sdate) { ret=true; }");
return ret;

}

USAGE:: alert(CompareTwoDates("01 January 2009","01 January
2010",">"))

Here in the UK it works fine. When I run this on an Italian server I
would expect JavaScript to use it's local settings and use Gennaio
instead of January, but it does not. It appears to continue to use
English Dates.
So my Italians are putting in things like CompareTwoDates("01 Gennaio
2009","01 Gennaio 2010",">") but the function is failing because
javascript does not understand the month Gennaio.

How can I tell JavaScript to use another language?

Thanks,
Graham
 
L

Laser Lips

Hi, I've got a script, which works with dates.
It compares two dates using an operand to test weather the first date
is '<', '>' or '=' to the second date.
Here it is.

function CompareTwoDates(firstDate,secondDate,operator)
{
        var tmp;
        // ConparisonType eg. <,>,= etc
        // first find out if either date is a datetime stamp
        if (firstDate.indexOf(":")!=-1)
        {
                // we assume there is a time portion to remove
                tmp=firstDate.split(" ");
                firstDate=tmp[0]+" "+tmp[1]+" "+tmp[2]
        }
        if (secondDate.indexOf(":")!=-1)
        {
                // we assume there is a time portion to remove
                tmp=secondDate.split(" ");
                secondDate=tmp[0]+" "+tmp[1]+" "+tmp[2]
        }
        var fdate=Date.parse(firstDate);
        var sdate=Date.parse(secondDate);
        var ret=false;

        if (isNaN(fdate)) return "Error. First argument is not a Date";
        if (isNaN(sdate)) return "Error. Second argument is not aDate";

        eval("if (fdate"+operator+"sdate) { ret=true; }");
        return ret;

}

USAGE:: alert(CompareTwoDates("01 January 2009","01 January
2010",">"))

Here in the UK it works fine. When I run this on an Italian server I
would expect JavaScript to use it's local settings and use Gennaio
instead of January, but it does not.  It appears to continue to use
English Dates.
So my Italians are putting in things like CompareTwoDates("01 Gennaio
2009","01 Gennaio 2010",">") but the function is failing because
javascript does not understand the month Gennaio.

How can I tell JavaScript to use another language?

Thanks,
Graham

Any help on this?
Cheers,
Graham
 
S

Scott Sauyet

would expect JavaScript to use it's local settings and use Gennaio
instead of January, but it does not.  It appears to continue to use
English Dates.
So my Italians are putting in things like CompareTwoDates("01 Gennaio
2009","01 Gennaio 2010",">") but the function is failing because
javascript does not understand the month Gennaio.

How can I tell JavaScript to use another language?

I may be mistaken, but I don't think you can tell Javascript that. I
think your function will need to do more work. You might start by
adding

CompareTwoDates.monthNames = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November",
"December"];

and then using the index of the month name in this array as part of
your algorithm. (I don't know if you also need "Jan", "Feb", "Mar",
etc. or not, but they would be easy to add.)

Then if it's running somewhere with a different language, you can just
override this array.

But I wonder if you've thought this through entirely. What happens if
run in the U.S., where traditional date formats are more like "January
6, 2010"?

Good luck,

-- Scott
 
T

Thomas 'PointedEars' Lahn

Scott said:
I may be mistaken, but I don't think you can tell Javascript that. I
think your function will need to do more work.

And the function needs a lot of work, too.
You might start by adding

CompareTwoDates.monthNames = [

The function identifier really should not start uppercase here.
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November",
"December"];

and then using the index of the month name in this array as part of
your algorithm. (I don't know if you also need "Jan", "Feb", "Mar",
etc. or not, but they would be easy to add.)

A possibility, but consider the implications. For mapping strings
to numbers is generally more efficient to use an Object instance:

CompareTwoDates.monthNames = {
"January": 0,
"February": 1,
"March": 2,
"April": 3,
"May": 4,
"June": 5,
...
};

Since it is rather tedious and potentially error-prone to do the counting
manually, the following loop can use the mapping nature inherent to all
ECMAScript objects to reuse your array for a map (just make sure no month
is named like a built-in property of Array instances; see also my Map
implementation):

for (var a = CompareTwoDates.monthNames,
i = a.length;
i--;)
{
a[a] = i;
}

Afterwards a["January"] (or a.January) would result in 0, a["February"] in
1 aso.

(It becomes a bit more complex if you also want to support abbreviations.)

The number can then be passed as second argument to the Date constructor in
order to have date values for the comparison.

However, it would be better if CompareTwoDates (better: compareTwoDates)
would also accept references to two Date instances, and instead of using
the third string argument returned a numeric value `r' indicating the
relation between the two (computed) date values (as it is customary: r < 0
Then if it's running somewhere with a different language, you can just
override this array.
ACK

But I wonder if you've thought this through entirely. What happens if
run in the U.S., where traditional date formats are more like "January
6, 2010"?

True. However, if there is always a month name or abbreviation, and the
year format is Y2K-safe (i.e., more than two digits), a Regular Expression
can handle the matching.


PointedEars
 
L

Laser Lips

Thanks for the responses.
This is legacy code. Stuff written, or should I say thrown together
by god knows who to get something working, so I take no responsibility
for it's ugliness.

I still don't understand why when this code runs on an Italian
browser, it does not understand Italian Months. If I hard code the
values to English months and run the code on the Italian browser, it
works as expected.

I would have thought JavaScript was language specific?

Obviously numerical arrays are the way to go, but this means rolling
this hack out over many environments with many different language
definitions. Not ideal, especially since we don't have locale settings
implemented on the front end yet.

Thanks again.
Graham
 
S

Scott Sauyet

And the function needs a lot of work, too.

Agreed. There's a real case to be made for replacing it altogether,
but I don't know the size of the code-base that uses it or the
timeframe for the current changes.
You might start by adding
    CompareTwoDates.monthNames = [

The function identifier really should not start uppercase here.
Agreed.
        "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November",
"December"];
and then using the index of the month name in this array as part of
your algorithm.  (I don't know if you also need "Jan", "Feb", "Mar",
etc. or not, but they would be easy to add.)

A possibility, but consider the implications.  For mapping strings
to numbers is generally more efficient to use an Object instance:

[ description of method to more efficiently store the look-ups deleted ]

Afterwards a["January"] (or a.January) would result in 0, a["February"] in
1 aso.

This would definitely perform better, but there is a complication in
that it would have to run after every time the list of month names is
updated. If you know that it happens in just one place in your script
and you can run this code afterward, it's fine, but it concerns me
some.

Of course you could add a function to replace the month names instead,
but now we're talking about an even bigger rewrite. (Not that this
function doesn't need it!)

However, it would be better if CompareTwoDates (better: compareTwoDates)
would also accept references to two Date instances, and instead of using
the third string argument returned a numeric value `r' indicating the
relation between the two (computed) date values (as it is customary: r < 0
if date1 < date2, r === 0 if date1 == date2, and r > 0 if date1> date2).  
Another misuse of eval() could be avoided that way.

That's clearly a better API, and it's one that most coders are used to
these days. But the OPs subsequent response makes me wonder how
difficult it would be to make that sort of change.

-- Scott
 
S

Scott Sauyet

This is legacy code.  Stuff written, or should I say thrown together
by god knows who to get something working, so I take no responsibility
for it's ugliness.

Been there, done that. The interface this function provides is not
ideal. If you can change it to one like Thomas Lahn suggested, that
would be your best bet. But that may not be an option. If not, then
some variation of what I suggested, probably with Thomas'
modifications is likely your best bet.

I would have thought JavaScript was language specific?

Remember that Javascript is a hack. It's an elegant hack, and can be
a very nice language to work in, but it was thrown together fairly
quickly, copied, then standardized without nearly as much thought as
often goes into other languages. Internationalization was not a major
consideration. Don't get me wrong, I really enjoy working in JS, but
it has a number of warts.
Obviously numerical arrays are the way to go, but this means rolling
this hack out over many environments with many different language
definitions. Not ideal, especially since we don't have locale settings
implemented on the front end yet.

Maybe this will be the impetus for that. :)

Good luck,

-- Scott
 
D

Dr J R Stockton

In comp.lang.javascript message <c018407e-03b4-43fa-b385-60a1a5d0ad48@b2
g2000yqi.googlegroups.com>, Tue, 5 Jan 2010 07:03:09, Laser Lips
Here in the UK it works fine. When I run this on an Italian server

The location of the server has no effect (and all servers should [appear
to] use GMT).
I
would expect JavaScript to use it's local settings and use Gennaio
instead of January, but it does not. It appears to continue to use
English Dates.

No : American :-( .

The locality does not necessarily correspond to the user's preference.
So my Italians are putting in things like CompareTwoDates("01 Gennaio
2009","01 Gennaio 2010",">") but the function is failing because
javascript does not understand the month Gennaio.

How can I tell JavaScript to use another language?

You tell ALL of your users to enter the date in the form YYYY-MM-DD (ISO
8601), which all users of the Gregorian Calendar with normal
intelligence can do. If time is needed, put that after as hh:mm:ss (no
am/pm). You match that with a RegExp to partly check they've got it
right. Then you compare the inputs as strings.

As long as they are told to give the order Y M D h m s, you can
alternatively do as indicated by

S = "2000 6 9"
M = S.match(/^(\d+)\D+(\d+)\D+(\d+)$/) // rigour optional
D = M[1]*1e4 + M[2]*1e2 + +M[3]

using M[x]||0 for fields not compulsory. Comparison will be arithmetic.

That even works for Julian, Hebrew and Islamic dates expressed with a
numeric month - al long as dates of different natures are not
intercompared.

It's a good idea to read the newsgroup c.l.j and its FAQ. See below.
 
D

David Mark

Been there, done that.  The interface this function provides is not
ideal.  If you can change it to one like Thomas Lahn suggested, that
would be your best bet.  But that may not be an option.  If not, then
some variation of what I suggested, probably with Thomas'
modifications is likely your best bet.


Remember that Javascript is a hack.

Javascript is not a hack. Lots of hacks attempt to write it (and
write about it), but they don't define the language.
 
L

Laser Lips

Dates going in as YYYY-MM-DD would be Ideal and in fact users are able
to put these in. The problem is after the input box looses focus, the
input (YYYY-MM-DD) gets turned into a string representation e.g. "01
Gennaio 2010", and then that's when CompareTwoDates get's called.

Users are able to enter dates in a number of different ways e.g.
121209 which will be evaluated to “12 December 2009”

So the string the function ends up working with is always the same
(which is one good thing at least)

I'm surprised this problem has not arisen before now because these
systems have been in place for years. I'm only just beginning to feel
the consequences of the previous programmers lack of foresight.

OK I’ve finally come up with a global solution that will work in most
languages, so long as the input format is “dd MMM yyyy”

function CompareTwoDates(firstDate,secondDate,operator)
{
var localMonths=[];
if(operator=="=")operator="==";

var englishMonth=Array
("January","February","March","April","May","June","July","August","September","October","November","December");
var d=new Date(),temp;
var mIndex=getMonthIndex();
//create an array of localised months
for(x=0;x<12;x++)
{
d.setMonth(x);
temp=d.toLocaleString();
temp=temp.split(" ");
temp=temp[mIndex].toUpperCase();
localMonths[temp]=x;
}

var d=new Date();
var tmp=firstDate.split(" ");
//turn days into an int (removes leading zero's)
tmp[0]++;tmp[0]--;
d.setDate(tmp[0]);
var tmonth=tmp[1];

d.setMonth(localMonths[tmonth.toUpperCase()]);
d.setFullYear(tmp[2]);
//recreate the date in english format
firstDate=d.getDate()+" "+englishMonth[d.getMonth()]+"
"+d.getFullYear();
//repeat for second date
var d=new Date();
tmp=secondDate.split(" ");
//turn days into an int (removes leading zero's)
tmp[0]++;tmp[0]--;
d.setDate(tmp[0]);
var tmonth=tmp[1];

d.setMonth(localMonths[tmonth.toUpperCase()]);
d.setFullYear(tmp[2]);
//recreate the date in english format
secondDate=d.getDate()+" "+englishMonth[d.getMonth()]+"
"+d.getFullYear();

// ConparisonType eg.<,>,= etc
var fdate=Date.parse(firstDate);
var sdate=Date.parse(secondDate);
var ret=false;
if (isNaN(fdate)) return "Error. First argument is not a Date";
if (isNaN(sdate)) return "Error. Second argument is not a Date";
eval("if (fdate"+operator+"sdate) { ret=true; }");
return ret;
}
function getMonthIndex()
{
var d=new Date().toLocaleString();
var t=d;
var manySpaces=0;
var hasSpace=true;
//remove time section
//if(d.indexOf(":")>-1)d=d.substring(0,d.indexOf(":"));

while(hasSpace==true)
{
if(t.indexOf(" ")>-1)
{
manySpaces++;
t=t.substring(t.indexOf(" ")+1);
}else{
hasSpace=false;
}
}

var changedArr=new Array(manySpaces);
var preArr=new Array(manySpaces);
var curArr=new Array(manySpaces);
for(var y=0;y<manySpaces;y++)
{
preArr[y]="";
changedArr[y]=0;
}
for(var x=0;x<12;x++)
{
d = new Date();
d.setMonth(x);
d=d.toLocaleString();
//if(d.indexOf(":")>-1)d=d.substring(0,d.indexOf(":"));
d=d.split(" ");
for(var y=0;y<manySpaces;y++)
{
curArr[y]=d[y];
if(preArr[y]!=curArr[y])
{
changedArr[y]++;
}
preArr[y]=curArr[y];
}
}
//now go through the changedArr and see which one changed the most.
//Month will be 12. Days will be second and be 7 at most
var ind=0;
for(var y=0;y<manySpaces;y++)
{
if(changedArr[y]==12)ind=y;
}
return ind;
}

alert(CompareTwoDates("02 March 2010","02 March 2010","<"))
// If your in Italiy
// alert(CompareTwoDates("02 Marzo 2010","02 Marzo 2010","<"))
// If your in French
// alert(CompareTwoDates("02 Mars 2010","02 Mars 2010","<"))
// If your in Germany
// alert(CompareTwoDates("02 März 2010","02 März 2010","<"))
 
S

Scott Sauyet

I know what hack means.  Thanks.  

You're very welcome.
Please stop citing random nonsense that does not support your position.

If I thought I were doing that, I would absolutely try to stop.

If, however, you think I'm doing so here, you must think that this
description of the meaning of "hack", best encapsulated by "an
appropriate application of ingenuity" does not describe Javascript.
If so, I disagree. JS is these days absolutely my favorite
programming language.

I'm not sure which of the main definitions of "hack" from the Jargon
File [1] is more apt; I think for me it depends upon what I'm trying
to accomplish with JS at the moment, but JS seems to be one of these:

1. n. Originally, a quick job that produces what is needed, but
not well.

2. n. An incredibly good, and perhaps very time-consuming, piece
of work that produces exactly what is needed.

And I stopped reading after the top headline:-

Then on what basis do you claim that the referenced page does not
support my position?

-- Scott
____________________
[1] http://catb.org/~esr/jargon/html/H/hack.html
 
D

Dr J R Stockton

In comp.lang.javascript message <2647c0ad-af63-49fe-8d14-a8d7a021b0ab@r1
4g2000vbc.googlegroups.com>, Wed, 6 Jan 2010 07:52:59, Scott Sauyet
But I wonder if you've thought this through entirely. What happens if
run in the U.S., where traditional date formats are more like "January
6, 2010"?

No problem, if new Date or Date.parse is used; one just translates the
alphabetical string (it might be possible, but would be grossly
unreasonable. to do that with a Google Translate call) since JavaScript
implementations are tolerant of field order provided that the day,
month, year substrings can be identified from their content.
 
D

David Mark

Scott said:
You're very welcome.


If I thought I were doing that, I would absolutely try to stop.

You've done it at least twice in 24 hours. Enough. You are very new
here, so the role of smart-ass is not becoming.
If, however, you think I'm doing so here, you must think that this
description of the meaning of "hack", best encapsulated by "an
appropriate application of ingenuity" does not describe Javascript.

Making up your own bizarre definitions for common terms is only going to
create confusion.
If so, I disagree. JS is these days absolutely my favorite
programming language.

Then start learning it and stop wasting time posting worthless links.
I'm not sure which of the main definitions of "hack" from the Jargon
File [1] is more apt; I think for me it depends upon what I'm trying
to accomplish with JS at the moment, but JS seems to be one of these:

1. n. Originally, a quick job that produces what is needed, but
not well.

That doesn't sound like JS at all to me.
2. n. An incredibly good, and perhaps very time-consuming, piece
of work that produces exactly what is needed.

Those are contradictory. What is the point of this?
Then on what basis do you claim that the referenced page does not
support my position?

Because I scanned the whole page as it came up and saw that it was a
bunch of nonsense that had nothing to add to this discussion. And it's
not as if "hack" needs any new interpretations anyway. Was my usage
unclear?
 
D

Dr J R Stockton

In comp.lang.javascript message <6798d613-fed9-408f-ba8b-17d3b35a55b1@r1
0g2000vbn.googlegroups.com>, Wed, 6 Jan 2010 10:06:24, Scott Sauyet
It's an elegant hack, and can be
a very nice language to work in, but it was thrown together fairly
quickly, copied, then standardized without nearly as much thought as
often goes into other languages. Internationalization was not a major
consideration.

Are you criticising standard US practice?
 
S

Scott Sauyet

function CompareTwoDates(firstDate,secondDate,operator)
{
        var tmp;
        // ConparisonType eg. <,>,= etc
        // first find out if either date is a datetime stamp
        if (firstDate.indexOf(":")!=-1)
        {
                // we assume there is a time portion to remove
                tmp=firstDate.split(" ");
                firstDate=tmp[0]+" "+tmp[1]+" "+tmp[2]
        }
        if (secondDate.indexOf(":")!=-1)
        {
                // we assume there is a time portion to remove
                tmp=secondDate.split(" ");
                secondDate=tmp[0]+" "+tmp[1]+" "+tmp[2]
        }
        var fdate=Date.parse(firstDate);
        var sdate=Date.parse(secondDate);
        var ret=false;

        if (isNaN(fdate)) return "Error. First argument is not a Date";
        if (isNaN(sdate)) return "Error. Second argument is not aDate";

        eval("if (fdate"+operator+"sdate) { ret=true; }");
        return ret;

}

USAGE:: alert(CompareTwoDates("01 January 2009","01 January
2010",">"))

Here in the UK it works fine. When I run this on an Italian server I
would expect JavaScript to use it's local settings and use Gennaio
instead of January, but it does not.  It appears to continue to use
English Dates.
So my Italians are putting in things like CompareTwoDates("01 Gennaio
2009","01 Gennaio 2010",">") but the function is failing because
javascript does not understand the month Gennaio.

Below is an altered version that allows you to set the month names
appropriately, based upon what I suggested below and upon some of
Thomas Lahn's suggestions.

CompareTwoDates = (function() {
var englishMonthNames = ["January", "February", "March",
"April", "May", "June", "July", "August", "September", "October",
"November", "December"];
var monthNames;
var result = function(firstDate,secondDate,operator) {
var tmp;
// ConparisonType eg. <,>,= etc
tmp=firstDate.split(" ");
firstDate=tmp[0]+" "+(monthNames[tmp[1].toLowerCase()] ||
tmp[1])+" "+tmp[2]
tmp=secondDate.split(" ");
secondDate=tmp[0]+" "+(monthNames[tmp[1].toLowerCase()] ||
tmp[1])+" "+tmp[2]

var fdate=Date.parse(firstDate);
var sdate=Date.parse(secondDate);
var ret=false;

if (isNaN(fdate)) return "Error. First argument is not a
Date";
if (isNaN(sdate)) return "Error. Second argument is not a
Date";

eval("if (fdate"+operator+"sdate) { ret=true; }");
return ret;
};
result.setMonthNames = function(newVals) {
if (newVals.length != 12) {
return "Error. There must be twelve month names";
}
monthNames = {};
for (var i = 0; i < 12; i++) {
monthNames[newVals.toLowerCase()] =
englishMonthNames;
}
}
result.setMonthNames(englishMonthNames);
return result;
})();

This is used just as you would the original, with the additional
feature that you can call

CompareTwoDates.setMonthNames(["Gennaio", "Febbraio", "Marzo",
"Aprile", "Maggio", "Giugno", "Luglio", "Agosto",
"Settembre", "Ottobre", "Novembre", "Dicembre"]);

at any time.

This does not substantially change your existing algorithm. The only
substantive differences are these:

(1) It always executes the code that previously only ran if there
was a time component. This doesn't harm anything, and gives you a
chance to hook into the rebuilding of the date string to do (2).
(2) It substitutes a new value the second component of the date
using an object that maps internationalized month names to their
English versions, defaulting to the English names.
(3) It adds the ability to set the month names using the user's
language, as described above.

It does this by storing the month names in a closure and maps them to
their English equivalents. The only error checking it does on the
date name is that they are supplied in a 12-element array. You might
want to add checks that each elements is a non-empty String and that
there are no duplicates. I leave that to you.

I am not suggesting that this is a good algorithm. I agree with
Thomas a better API would involve returning a positive or negative
number or zero depending upon whether the first date is later than,
earlier than, or the same as the second. But if you need to keep your
API, this function should serve as a drop-in replacement.

You still need to get to front-end locale settings in order to use it,
but once done, this might fit your needs.

Good luck,

-- Scott
 
L

Laser Lips

function CompareTwoDates(firstDate,secondDate,operator)
{
        var tmp;
        // ConparisonType eg. <,>,= etc
        // first find out if either date is a datetime stamp
        if (firstDate.indexOf(":")!=-1)
        {
                // we assume there is a time portion toremove
                tmp=firstDate.split(" ");
                firstDate=tmp[0]+" "+tmp[1]+" "+tmp[2]
        }
        if (secondDate.indexOf(":")!=-1)
        {
                // we assume there is a time portion toremove
                tmp=secondDate.split(" ");
                secondDate=tmp[0]+" "+tmp[1]+" "+tmp[2]
        }
        var fdate=Date.parse(firstDate);
        var sdate=Date.parse(secondDate);
        var ret=false;
        if (isNaN(fdate)) return "Error. First argument is not a Date";
        if (isNaN(sdate)) return "Error. Second argument is nota Date";
        eval("if (fdate"+operator+"sdate) { ret=true; }");
        return ret;

USAGE:: alert(CompareTwoDates("01 January 2009","01 January
2010",">"))
Here in the UK it works fine. When I run this on an Italian server I
would expect JavaScript to use it's local settings and use Gennaio
instead of January, but it does not.  It appears to continue to use
English Dates.
So my Italians are putting in things like CompareTwoDates("01 Gennaio
2009","01 Gennaio 2010",">") but the function is failing because
javascript does not understand the month Gennaio.

Below is an altered version that allows you to set the month names
appropriately, based upon what I suggested below and upon some of
Thomas Lahn's suggestions.

    CompareTwoDates = (function() {
        var englishMonthNames = ["January", "February", "March",
"April", "May", "June", "July", "August", "September", "October",
"November", "December"];
        var monthNames;
        var result = function(firstDate,secondDate,operator) {
            var tmp;
            // ConparisonType eg. <,>,= etc
            tmp=firstDate.split(" ");
            firstDate=tmp[0]+" "+(monthNames[tmp[1].toLowerCase()] ||
tmp[1])+" "+tmp[2]
            tmp=secondDate.split(" ");
            secondDate=tmp[0]+" "+(monthNames[tmp[1].toLowerCase()] ||
tmp[1])+" "+tmp[2]

            var fdate=Date.parse(firstDate);
            var sdate=Date.parse(secondDate);
            var ret=false;

            if (isNaN(fdate)) return "Error. First argument is not a
Date";
            if (isNaN(sdate)) return "Error. Second argument is not a
Date";

            eval("if (fdate"+operator+"sdate) { ret=true; }");
            return ret;
        };
        result.setMonthNames = function(newVals) {
            if (newVals.length != 12) {
                return "Error. There must be twelve monthnames";
            }
            monthNames = {};
            for (var i = 0; i < 12; i++) {
                monthNames[newVals.toLowerCase()] =
englishMonthNames;
            }
        }
        result.setMonthNames(englishMonthNames);
        return result;
    })();

This is used just as you would the original, with the additional
feature that you can call

    CompareTwoDates.setMonthNames(["Gennaio", "Febbraio", "Marzo",
        "Aprile", "Maggio", "Giugno", "Luglio", "Agosto",
        "Settembre", "Ottobre", "Novembre", "Dicembre"]);

at any time.

This does not substantially change your existing algorithm.  The only
substantive differences are these:

    (1) It always executes the code that previously only ran if there
was a time component.  This doesn't harm anything, and gives you a
chance to hook into the rebuilding of the date string to do (2).
    (2) It substitutes a new value the second component of the date
using an object that maps internationalized month names to their
English versions, defaulting to the English names.
    (3) It adds the ability to set the month names using the user's
language, as described above.

It does this by storing the month names in a closure and maps them to
their English equivalents.  The only error checking it does on the
date name is that they are supplied in a 12-element array.  You might
want to add checks that each elements is a non-empty String and that
there are no duplicates.  I leave that to you.

I am not suggesting that this is a good algorithm.  I agree with
Thomas a better API would involve returning a positive or negative
number or zero depending upon whether the first date is later than,
earlier than, or the same as the second.  But if you need to keep your
API, this function should serve as a drop-in replacement.

You still need to get to front-end locale settings in order to use it,
but once done, this might fit your needs.

Good luck,

  -- Scott


Thanks Scott, but I prefer my solution because I need not know what
country the code is running in and I wont need to pass all the country
specific months. I also won't have to change any code already calling
this function.

Thanks all
Graham
 
S

Scott Sauyet

You've done it at least twice in 24 hours.  Enough.  You are very new
here, so the role of smart-ass is not becoming.

If you're referring to this post

http://groups.google.com/group/comp.lang.javascript/msg/eab3be4c311689c4

then I beg to differ. When you claimed, "I certainly don't "watch"
any jQuery lists. And I never trumpet anything in here," I pointed to
five separate threads you'd initiated in the past month. Each of
those initial posts involved a critique of jQuery. Four of them
referred directly to posts in the jQuery forum.

I am not citing random nonsense that does not support my position. In
fact, I've stated no position on this matter. I simply supplied some
evidence that your statement was incorrect.

As to the other matter, how long does one have to hang out here to be
allowed to act as a smart-ass? Because I'd much rather do that than
act like some of the dumb-asses that have been posting here for a
longer time.

Making up your own bizarre definitions for common terms is only going to
create confusion.

Rather, quoting one of the best-known authorities on hacking might
help settle some confusion.

Then start learning it and stop wasting time posting worthless links.

I am trying to learn it better. That's what I'm doing in these parts.

A worthless link is still better than attempting a serious rebuttal of
a rhetorical flourish such as the first sentence of the following

| Remember that Javascript is a hack. It's an elegant hack, and can
be
| a very nice language to work in, but it was thrown together fairly
| quickly, copied, then standardized without nearly as much thought as
| often goes into other languages. Internationalization was not a
major
| consideration. Don't get me wrong, I really enjoy working in JS,
but
| it has a number of warts.

with something like this:

| Javascript is not a hack. Lots of hacks attempt to write it (and
| write about it), but they don't define the language.

Posting that seems fairly worthless. It doesn't doesn't rebut,
refine, or elaborate the substance of the paragraph it was responding
to. It picks out one word, and makes what is essentially a pun on
that word, and responds to the altered meaning of that one word. That
is pure sophism. (Or there is some sort of language barrier in play?)

I shouldn't have responded. But I didn't want the nonsense you
supplied to be the last word on that subject.

Because I scanned the whole page as it came up and saw that it was a
bunch of nonsense that had nothing to add to this discussion.

None of this has anything to do with helping the OP address his
problem. The paragraph to which you responded was at least an attempt
to explain *why* the problem existed. Do you really claim that your
"not a hack" comment added something of value to the discussion?

And it's not as if "hack" needs any new interpretations anyway.

No, the one commonly used among programmers, is probably a good
start. Do you know what that is?

Was my usage unclear?

Excuse me. Is your ego really large enough to think that your usage
of the word is what matters when you were the one who jumped in to say
that my usage was incorrect? No wonder you think your library and
your putative book deal are so much better than any other JS sources
that exist.

-- Scott
 
S

Scott Sauyet

Thanks Scott, but I prefer my solution because I need not know what
country the code is running in and I wont need to pass all the country
specific months. I also won't have to change any code already calling
this function.

I hadn't seen your solution when I posted mine. You definitely don't
want to have to supply the locale strings if they're not needed. I
hadn't come up with a way to avoid it. I'm glad you did.

That's a clever use of toLocaleString() in your code.

-- Scott
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top