sorting dates

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • mike

    sorting dates

    If I had a date in the format "01-Jan-05" it does not sort properly
    with my sort routine:

    function compareDate(a,b )
    {
    var date_a = new Date(a);
    var date_b = new Date(b);
    if (date_a < date_b)
    { return -1; }
    else
    {
    if (date_a > date_b)
    { return 1; }
    else
    { return 0; }
    }
    }

    I guess it expects the date in mm/dd/yyyy format.

    Do I have to change:

    var date_a = new Date(a);
    var date_b = new Date(b);

    so it recognizes a correct format?

    Mike

  • RobG

    #2
    Re: sorting dates

    mike wrote:[color=blue]
    > If I had a date in the format "01-Jan-05" it does not sort properly
    > with my sort routine:[/color]

    The arguments for Date() are:

    Date( [year[, month[, date[, hours[, minutes[, seconds[, ms]]]]]]])

    All arguments are optional.
    [color=blue]
    >
    > function compareDate(a,b )
    > {
    > var date_a = new Date(a);[/color]

    Assuming input is as posted and noting that months are numbered from 0
    to 11:

    var months = {'jan':0, 'feb':1, 'mar':2, 'apr':3, 'may':4, 'jun':5,
    'jul':6, 'aug':7, 'sep':8, 'oct':9, 'nov':10, 'dec':11 };
    var aBits = a.split('-');
    var date_a = new Date( a[2], months[a[1].toLowerCase()], a[0] );

    and the same for b. Note that you should validate all input first and
    that 'date_a' is a valid date for whatever purpose you intend to use it for.

    e.g. if '00-Jul-2005' is input, the resulting date will be 30-Jun-2005.
    '32-Jul-2005' gives 01-Aug-2005


    [color=blue]
    > var date_b = new Date(b);
    > if (date_a < date_b)
    > { return -1; }
    > else
    > {
    > if (date_a > date_b)
    > { return 1; }
    > else
    > { return 0; }
    > }
    > }
    >
    > I guess it expects the date in mm/dd/yyyy format.[/color]

    No, 'it' doesn't. There is a lot more stuff on dates here:

    <URL:http://www.merlyn.demo n.co.uk/js-dates.htm>


    [...]

    --
    Rob

    Comment

    • mike

      #3
      Re: sorting dates

      Rob thanks i can understand what is goin on there.

      works fine.

      Comment

      • RobG

        #4
        Re: sorting dates

        RobG wrote:[color=blue]
        > mike wrote:
        >[color=green]
        >> If I had a date in the format "01-Jan-05" it does not sort properly
        >> with my sort routine:[/color][/color]

        As a hint, simply reformatting as yyyy-mm-dd will sort correctly (and be
        in an ISO acceptable format that is recognised internationally ). There
        is no need for using date objects at all (though you may wish to use
        them to validate your dates before attempting to sort them).

        Below is a simple example, no validation of input or dates is attempted
        but would be required in practice.

        I have kept the months as zero-indexed - you may wish to change that.


        <script type="text/javascript">

        var months = { 'jan':0, 'feb':1, 'mar':2, 'apr':3,
        'may':4, 'jun':5, 'jul':6, 'aug':7,
        'sep':8, 'oct':9, 'nov':10, 'dec':11 };

        function sortDates(){
        var D = [];
        var i = arguments.lengt h;
        while ( i-- ) {
        D[i] = formatAsYMD( arguments[i] );
        }
        return D.sort();
        }

        function formatAsYMD( str ) {
        var x = str.split('-');
        return x[2] + '-'
        + addZ( months[x[1].toLowerCase()] ) + '-'
        + addZ( x[0] );
        }

        function addZ( x ) {
        return ( x < 10 )? '0' + x : x;
        }

        </script>

        <form action="">
        <input name="dStrA" value="28-Jul-2005">
        <input name="dStrB" value="28-Aug-2005">
        <input name="dStrC" value="2-Feb-2003">
        <input type="button" value="show date" onclick="
        alert( sortDates(
        this.form.dStrA .value,
        this.form.dStrB .value,
        this.form.dStrC .value
        )
        );
        ">

        </form>
        [color=blue]
        >
        >
        > The arguments for Date() are:
        >
        > Date( [year[, month[, date[, hours[, minutes[, seconds[, ms]]]]]]])
        >
        > All arguments are optional.
        >[color=green]
        >>
        >> function compareDate(a,b )
        >> {
        >> var date_a = new Date(a);[/color]
        >
        >
        > Assuming input is as posted and noting that months are numbered from 0
        > to 11:
        >
        > var months = {'jan':0, 'feb':1, 'mar':2, 'apr':3, 'may':4, 'jun':5,
        > 'jul':6, 'aug':7, 'sep':8, 'oct':9, 'nov':10, 'dec':11 };
        > var aBits = a.split('-');
        > var date_a = new Date( a[2], months[a[1].toLowerCase()], a[0] );
        >
        > and the same for b. Note that you should validate all input first and
        > that 'date_a' is a valid date for whatever purpose you intend to use it
        > for.
        >
        > e.g. if '00-Jul-2005' is input, the resulting date will be 30-Jun-2005.
        > '32-Jul-2005' gives 01-Aug-2005
        >
        >
        >[color=green]
        >> var date_b = new Date(b);
        >> if (date_a < date_b)
        >> { return -1; }
        >> else
        >> {
        >> if (date_a > date_b)
        >> { return 1; }
        >> else
        >> { return 0; }
        >> }
        >> }[/color][/color]

        And that could be:

        return ( a < b );
        [color=blue][color=green]
        >>
        >> I guess it expects the date in mm/dd/yyyy format.[/color]
        >
        >
        > No, 'it' doesn't. There is a lot more stuff on dates here:
        >
        > <URL:http://www.merlyn.demo n.co.uk/js-dates.htm>
        >
        >
        > [...]
        >[/color]


        --
        Rob

        Comment

        • mike

          #5
          Re: sorting dates

          Ron,

          i am pulling the dates from Oracle and they are in that 27-Jul-05
          format. I'd like to change them by using some oracle functions or
          coldfusion functions but am unable to (this would be another subject
          alltogether) until it gets to the page. The data is loaded to the page
          in an array is loaded dynamically. The user has the choice of sorting
          the columns, thus the array needs to be sorted and reapplied to the
          page.

          The page does not know how many fields will be in the array page or
          what order they will be. The user selected them on the previous page.

          So thanks for your help.I think that will work and I'll going to chek
          out this other code as well.

          Comment

          • fox

            #6
            Re: sorting dates



            mike wrote:[color=blue]
            > Ron,
            >
            > i am pulling the dates from Oracle and they are in that 27-Jul-05
            > format. I'd like to change them by using some oracle functions or
            > coldfusion functions but am unable to (this would be another subject
            > alltogether) until it gets to the page. The data is loaded to the page
            > in an array is loaded dynamically. The user has the choice of sorting
            > the columns, thus the array needs to be sorted and reapplied to the
            > page.
            >
            > The page does not know how many fields will be in the array page or
            > what order they will be. The user selected them on the previous page.
            >
            > So thanks for your help.I think that will work and I'll going to chek
            > out this other code as well.
            >[/color]

            // a little conversion shortcut

            var mos = { Jan:"01",
            Feb:"02",
            Mar:"03",
            Apr:"04",
            May:"05",
            Jun:"06",
            Jul:"07",
            Aug:"08",
            Sep:"09",
            Oct:"10",
            Nov:"11",
            Dec:"12"
            };

            String.prototyp e.oracleDateVal ue = function()
            {
            return this.replace(/(\d+)-(\w+)-(\d+)/,
            function(s, p1, p2, p3)
            {
            return "20" + p3 + mos[p2] + p1;
            });
            }


            function
            oracleDateCompa re(a,b)
            {
            return a.oracleDateVal ue() - b.oracleDateVal ue();
            }


            oracleDatesArra y.sort(oracleDa teCompare);


            ** I have assumed that oracle uses leading zeros where necessary, ex:

            01-Jun-00 for June 1, 2000

            if not, you can force leading zeros for dates (and months) with:

            ("0" + p1).replace(/(\d\d)$/,"$1");


            anyway, the oracleDateValue should return an integer in YYYYMMDD format
            (year 2000 >) which sorts quite easily.


            to answer your previous post:

            String.prototyp e.oracleDate2Co mmon = function()
            {

            return this.replace(/(\d+)-(\w+)-(\d+)/,
            function(s, p1, p2, p3)
            {
            return mos[p2].replace(/^0/,"") + "/" +
            p1.replace(/^0/,"") + "/20" + p3;
            });
            }



            will convert 25-Aug-05 to 8/5/2005

            you can simplify the expression by setting up the mos object without
            leading zeros.



            Comment

            • RobG

              #7
              Re: sorting dates

              fox wrote:[color=blue]
              >
              >
              > mike wrote:
              >[/color]
              [...][color=blue]
              > String.prototyp e.oracleDateVal ue = function()
              > {
              > return this.replace(/(\d+)-(\w+)-(\d+)/,
              > function(s, p1, p2, p3)
              > {
              > return "20" + p3 + mos[p2] + p1;
              > });[/color]

              Function arguments in String.replace( ) are not supported in some
              browsers, e.g. Safari and according to Mike Winter:

              "... IE5 and earlier ... don't support function arguments, and
              Opera 6 won't perform a replacement at all (a no-op)."

              There may be others.

              Returned strings should probably contain delimiters (say '-') to make
              them more obviously dates (yyyy-mm-dd). Sorting should be unaffected.

              [...]


              --
              Rob

              Comment

              • fox

                #8
                Re: sorting dates



                RobG wrote:[color=blue]
                > fox wrote:
                >[color=green]
                >>
                >>
                >> mike wrote:
                >>[/color]
                > [...]
                >[color=green]
                >> String.prototyp e.oracleDateVal ue = function()
                >> {
                >> return this.replace(/(\d+)-(\w+)-(\d+)/,
                >> function(s, p1, p2, p3)
                >> {
                >> return "20" + p3 + mos[p2] + p1;
                >> });[/color]
                >
                >
                > Function arguments in String.replace( ) are not supported in some
                > browsers, e.g. Safari and according to Mike Winter:
                >
                > "... IE5 and earlier ... don't support function arguments, and
                > Opera 6 won't perform a replacement at all (a no-op)."[/color]

                [color=blue]
                >
                > There may be others.[/color]

                That is a PISS POOR argument. From whom are you repeating it?


                [my take on these other browsers]
                Until these browsers get their numbers up... they don't matter -- not to
                my clients, and therefore, not to me.

                My clients are business people... they want sites for other business
                people... they're ALL using PCs with some form of Windows and using IE
                as their browser. In the past 2 years, I've talked with exactly 1
                "prospectiv e" client that used Firefox (so NOT a problem for me!). It
                would seem the only people around here (i.e., in the area where I live)
                using "off-brand" browsers are the programmers -- and that "prospectiv e"
                client just picked my brain a little, then did the work himself.


                So, 100% of my clients use IE5.5+ -- when I ask about Netscape or "other
                browser" support -- oddly enough -- THEY don't care (I do a LOT of work
                I don't have to do -- but I DO draw a line)... Everybody THEY know uses IE.

                Safari has so many other problems with it -- I only use it to read my
                daily news... any serious surfing on the Mac and I go to Firefox.

                Opera SUCKED so badly early on -- i gave up after the v3 (i think) --
                and it's numbers are still so low... they're just one of the arguments
                for those who keep saying "you can't do something because..." Besides --
                don't you have to pay for opera? It will never be a contender.

                [back to topic]
                And what exactly is keeping these browsers from supporting this feature?
                Even *I* can write the code that handles functions in replace:

                String.prototyp e.replace2 = function()
                {

                if(arguments.le ngth < 2) return null; // or whatever...

                var re = arguments[0];
                var replacement = arguments[1];

                var matches = this.match(re);

                if(typeof replacement == "function")
                {
                return replacement( matches[0],
                matches[1],
                matches[2],
                matches[3],
                matches[4],
                matches[5],
                matches[6],
                matches[7],
                matches[8],
                matches[9]);
                }
                else
                {
                return "I'll leave the rest as an exercise!";
                // $1..$9 must be accounted for...
                // hence, (hint) the matches array from 0 to 9
                }
                }


                and then (even with just this little bit) my little date "turnaround s"
                WILL work in Safari [tested] (as well as IE, and Mozilla(s)); [I won't
                even install Opera anymore so -- no tellin'... I will assume Konqueror
                has similar problems as Safari is based on it]


                Finally -- Just because something doesn't work in all browsers, doesn't
                mean that with a little effort, it can't be made to work. I'm tired of
                all the laziness of those who sit back and criticize or complain that
                something cannot be used because some pitiful relatively insignificant
                browser doesn't support the feature when worthwhile solutions to
                problems can be found. This one was easy (it took considerably longer to
                write this response than it did to come up with the solution - about 8
                minutes). I don't let a little thing like "minor browser" disfunction
                stand in my way. Why do you? Because somebody *else* said so?

                [color=blue]
                >
                > Returned strings should probably contain delimiters (say '-') to make
                > them more obviously dates (yyyy-mm-dd). Sorting should be unaffected.
                >[/color]

                comparing strings no doubt takes longer than comparing numbers.

                if all dates to be sorted are in YYYY-MM-DD format, and -- worst case,
                they are all in the first week of the same year and month, then the
                MINIMUM # of comparisons needed to be made to pass one as <> the other
                would be 10 (one per character as long as they are equal) - two week
                span, 9 -- etc... Unless, of course, JavaScript can compare "chunks" of
                strings in one "throw" (I used to do it in C -- up to 8 characters at a
                time -- typecast to longints -- really good way to speed up searches too)


                with integers:
                2 numbers, 1 subtraction... you do the math...

                [but this only matters if the operations are "time-critical"]

                oh... that little YYYYMMDD integer format -- it's called a "packed" date
                format (packing integers is a "time-honored programming tradition") --
                been around for considerably longer than JavaScript. Technically, the
                "digits" should be hexadecimal, but for sorting purposes, decimal digits
                work just as well with the extra added benefit of being easily readable
                in human terms.
                [color=blue]
                > [...]
                >
                >[/color]









                Comment

                • RobG

                  #9
                  Re: sorting dates

                  fox wrote:
                  [...][color=blue][color=green]
                  >> Function arguments in String.replace( ) are not supported in some
                  >> browsers, e.g. Safari and according to Mike Winter:
                  >>
                  >> "... IE5 and earlier ... don't support function arguments, and
                  >> Opera 6 won't perform a replacement at all (a no-op)."
                  >>
                  >> There may be others.[/color]
                  >
                  >
                  > That is a PISS POOR argument. From whom are you repeating it?[/color]

                  The attribution is right where I posted it. It came from another
                  thread where you also proposed using functions with the replace
                  method. It is useful to point out to others where things may fail -
                  what they choose to do with that advice is completely up to them.
                  [color=blue]
                  > [my take on these other browsers]
                  > Until these browsers get their numbers up... they don't matter -- not to
                  > my clients, and therefore, not to me.[/color]

                  Whatever is posted here is expected to be suitable for the web in
                  general and not be specific to intranets or corporate clients. If
                  specific advice has know limitations then they should be noted so that
                  others may decide for themselves whether it suits their circumstance
                  or not.

                  Excluding certain browsers purely on the basis that they are a small
                  minority is not reasonable.

                  [...]
                  [color=blue][color=green]
                  >> Returned strings should probably contain delimiters (say '-') to make
                  >> them more obviously dates (yyyy-mm-dd). Sorting should be unaffected.
                  >>[/color]
                  >
                  > comparing strings no doubt takes longer than comparing numbers.
                  >
                  > if all dates to be sorted are in YYYY-MM-DD format, and -- worst case,
                  > they are all in the first week of the same year and month, then the
                  > MINIMUM # of comparisons needed to be made to pass one as <> the other
                  > would be 10 (one per character as long as they are equal) - two week
                  > span, 9 -- etc... Unless, of course, JavaScript can compare "chunks" of
                  > strings in one "throw" (I used to do it in C -- up to 8 characters at a
                  > time -- typecast to longints -- really good way to speed up searches too)[/color]

                  The idea is to have them in a format that sort() can use without any
                  further modification and that doesn't require a comparison function.
                  Whether they are strings or numbers will likely make very little
                  difference in the OP's case as whatever operations are done to the
                  table rows will likely take far, far longer than the actual sort.
                  [color=blue]
                  > with integers:
                  > 2 numbers, 1 subtraction... you do the math...[/color]

                  Unless you know the actual internal algorithm of how the sort works,
                  discussing what you think it might be doing means you are basing your
                  argument on conjecture.
                  [color=blue]
                  >
                  > [but this only matters if the operations are "time-critical"]
                  >
                  > oh... that little YYYYMMDD integer format -- it's called a "packed" date
                  > format (packing integers is a "time-honored programming tradition") --
                  > been around for considerably longer than JavaScript. Technically, the
                  > "digits" should be hexadecimal, but for sorting purposes, decimal digits
                  > work just as well with the extra added benefit of being easily readable
                  > in human terms.[/color]

                  So you know some other names for that format - bravo. I made no
                  assertion that it was peculiar to JavaScript - I know it isn't.

                  I suggested the ISO standard format since it is an international
                  standard that is unambiguous and widely understood and therefore very
                  well suited for the web. It also sorts effortlessly and therefore is
                  likely suitable for this and many other purposes.

                  The OP may think it's a load of crap and totally ignore everything I
                  posted - ain't life grand.


                  --
                  Rob

                  Comment

                  • mike

                    #10
                    Re: sorting dates

                    As the OP is appreciate the help, but not the bickering much.

                    My opinion: I really don't have the time to write code for each
                    browser. It depends on who the user is. I have a neighborhood site
                    where there are alot of older people and some of them have macs, and
                    some netscape, but mostly ie. Still i have to write generic code for
                    them.

                    I prefer to write for IE, because of the dhtml. I have some pages that
                    support only ie and i tell the user up front, i.e. they can't login
                    unless they are using IE. If they dont have IE they can't play.

                    I really appreciate all the posters help here though, and comments.

                    Mike

                    Comment

                    • Lee

                      #11
                      Re: sorting dates

                      mike said:
                      [color=blue]
                      >I prefer to write for IE, because of the dhtml.[/color]

                      That hasn't really been a good reason for several years, has it?

                      Forcing non-technical people to use IE is like the Post Office
                      requiring that they leave their doors unlocked if they want their
                      mail delivered.

                      Comment

                      • Dr John Stockton

                        #12
                        Re: sorting dates

                        JRS: In article <1122594500.080 214.8260@g47g20 00cwa.googlegro ups.com>,
                        dated Thu, 28 Jul 2005 16:48:20, seen in news:comp.lang. javascript, mike
                        <hillmw@charter .net> posted :[color=blue]
                        >If I had a date in the format "01-Jan-05" it does not sort properly
                        >with my sort routine:[/color]
                        [color=blue]
                        >I guess it expects the date in mm/dd/yyyy format.[/color]

                        So see what new Date() makes of such a string; don't try too much at
                        once. I get NaN for it.

                        Don't rely on browsers to recognise mm/dd/yyyy, a.k.a. FFF; it's not
                        specified, and may depend on localisation. Eschew FFF utterly on the
                        Internet.

                        My first post in the thread you started earlier indicated how to read
                        your date format; the cited Web page shows how to convert it to an ISO
                        8601 string and/or to a date object; ISO strings sort directly. Date
                        Objects, IIRC, are by default sorted alphabetically on the result of
                        ..toString() - inefficient and wrong - but you only need
                        function Compare DateObjects(D1, D2) { return D2-D1 }
                        IIRC - see my js-dates.htm#SbDT

                        Read the FAQ; see below.

                        --
                        © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                        <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
                        <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                        <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                        Comment

                        • Dr John Stockton

                          #13
                          Re: sorting dates

                          JRS: In article <dccq76$22i$1@n ews.datasync.co m>, dated Fri, 29 Jul
                          2005 03:43:07, seen in news:comp.lang. javascript, fox
                          <spamtrap@fxmah oney.com> posted :[color=blue]
                          >
                          >
                          >comparing strings no doubt takes longer than comparing numbers.[/color]

                          Perhaps so. But the comparison operator should be implemented at the
                          ASM level or similar; so, for strings of the length in question, ISTM
                          reasonably likely that the overall time will be dominated by other parts
                          of the routine. If it matters, it should be tested.

                          With 8-character strings, using the quickest test loop I know, I find
                          the loop for comparison of equal 8-character Strings to be about 10%
                          slower than that for the corresponding Numbers, loop overhead being
                          about 20%. Other browsers are likely to differ.

                          [color=blue]
                          >if all dates to be sorted are in YYYY-MM-DD format, and -- worst case,
                          >they are all in the first week of the same year and month, then the
                          >MINIMUM # of comparisons needed to be made to pass one as <> the other
                          >would be 10 (one per character as long as they are equal) - two week
                          >span, 9 -- etc... Unless, of course, JavaScript can compare "chunks" of
                          >strings in one "throw" (I used to do it in C -- up to 8 characters at a
                          >time -- typecast to longints -- really good way to speed up searches too)[/color]

                          IIRC, the PC CPU instruction set provides for efficient comparisons of
                          strings of 8-bit characters, and may do so, intentionally or otherwise,
                          foe 16-bit ones.

                          [color=blue]
                          >oh... that little YYYYMMDD integer format -- it's called a "packed" date
                          >format (packing integers is a "time-honored programming tradition") --
                          >been around for considerably longer than JavaScript. Technically, the
                          >"digits" should be hexadecimal, but for sorting purposes, decimal digits
                          >work just as well with the extra added benefit of being easily readable
                          >in human terms.[/color]

                          It's not rightly called "packed". When discussing ISO 8601 formats, one
                          should use ISO 8601 terminology.

                          The string 'YYYYMMDD' is "Basic format".
                          The string 'YYYY-MM-DD' is "Extended format".

                          A Basic format string can (with unary +) be converted to a javascript
                          Number; but that is an IEEE Double, not an integer. Numbers in
                          javascript do not have decimal digits.

                          --
                          © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
                          Web <URL:http://www.merlyn.demo n.co.uk/> - w. FAQish topics, links, acronyms
                          PAS EXE etc : <URL:http://www.merlyn.demo n.co.uk/programs/> - see 00index.htm
                          Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.

                          Comment

                          • fox

                            #14
                            Re: sorting dates



                            RobG wrote:[color=blue]
                            > fox wrote:
                            > [...]
                            >[color=green][color=darkred]
                            >>> Function arguments in String.replace( ) are not supported in some
                            >>> browsers, e.g. Safari and according to Mike Winter:
                            >>>
                            >>> "... IE5 and earlier ... don't support function arguments, and
                            >>> Opera 6 won't perform a replacement at all (a no-op)."
                            >>>
                            >>> There may be others.[/color]
                            >>
                            >>
                            >>
                            >> That is a PISS POOR argument. From whom are you repeating it?[/color]
                            >
                            >
                            > The attribution is right where I posted it. It came from another thread
                            > where you also proposed using functions with the replace method. It is
                            > useful to point out to others where things may fail - what they choose
                            > to do with that advice is completely up to them.[/color]

                            solutions are better than advice... interesting that you deleted mine
                            from this post
                            [color=blue]
                            >[color=green]
                            > > [my take on these other browsers][/color]
                            >[color=green]
                            >> Until these browsers get their numbers up... they don't matter -- not
                            >> to my clients, and therefore, not to me.[/color]
                            >
                            >
                            > Whatever is posted here is expected to be suitable for the web in
                            > general and not be specific to intranets or corporate clients. If
                            > specific advice has know limitations then they should be noted so that
                            > others may decide for themselves whether it suits their circumstance or
                            > not.[/color]

                            So -- it's just about "lightweigh t solutions for lightweight browsers"
                            -- right?

                            Comply or Die worked against Netscape 4. So why not all the others? Now
                            it's "let's mollycoddle all these poor minority browsers to give them a
                            chance to survive?" Don't make me laugh.

                            [color=blue]
                            >
                            > Excluding certain browsers purely on the basis that they are a small
                            > minority is not reasonable.[/color]

                            It's more than reasonable -- it's called competition... If "minority"
                            browsers can't pull it together enough to survive... they are doomed to
                            die out... I am not compelled to hold back anything to accommodate poor
                            impelementation s. If these minority browsers want to survive, they have
                            to fix their shortcomings... that's all there is to it. Before you take
                            further issue with this, I am merely reflecting the attitude of all of
                            those on this and other newsgroups when everybody couldn't wait for
                            Netscape 4 to "die and go away"... that precedence has been set.


                            String.replace with function as second argument was implemented in
                            JavaScript 1.3 -- FULLY six years ago. There is NO excuse. ECMA
                            describes String.prototyp e.replace with the first case for the second
                            argument (replaceValue) as a *function.* There IS no excuse. I am fully
                            justified to offer string.replace options with functions as second
                            arguments.
                            [color=blue]
                            >
                            > [...]
                            >[color=green][color=darkred]
                            >>> Returned strings should probably contain delimiters (say '-') to make
                            >>> them more obviously dates (yyyy-mm-dd). Sorting should be unaffected.
                            >>>[/color]
                            >>
                            >> comparing strings no doubt takes longer than comparing numbers.
                            >>
                            >> if all dates to be sorted are in YYYY-MM-DD format, and -- worst case,
                            >> they are all in the first week of the same year and month, then the
                            >> MINIMUM # of comparisons needed to be made to pass one as <> the other
                            >> would be 10 (one per character as long as they are equal) - two week
                            >> span, 9 -- etc... Unless, of course, JavaScript can compare "chunks"
                            >> of strings in one "throw" (I used to do it in C -- up to 8 characters
                            >> at a time -- typecast to longints -- really good way to speed up
                            >> searches too)[/color]
                            >
                            >
                            > The idea is to have them in a format that sort() can use without any
                            > further modification and that doesn't require a comparison function.
                            > Whether they are strings or numbers will likely make very little
                            > difference in the OP's case as whatever operations are done to the table
                            > rows will likely take far, far longer than the actual sort.
                            >[color=green]
                            >> with integers:
                            >> 2 numbers, 1 subtraction... you do the math...[/color]
                            >
                            >
                            > Unless you know the actual internal algorithm of how the sort works,
                            > discussing what you think it might be doing means you are basing your
                            > argument on conjecture.[/color]


                            Offhand, I don't for sure -- but I've seen enough of them to guess...
                            probably quicksort...

                            I'm basing my argument on the "typical" sorting algorithms I have come
                            across (as well as written from the ground up) in "my time." I'm also
                            weighing in the algorithms I have worked out for myself. For strings,
                            the "typical" algorithm compares one character (code) at a time until
                            there is a difference, at which point the choice of order is made. For
                            long strings, this can be a "lengthy" process, all things being
                            relative. Atypical algorithms will optimize comparisons by measuring
                            data, then "biting" it off a "register" at a time. 64-bit registers have
                            been around for some time now, so that means 8 characters at a time.
                            Eight characters can be typecast to an unsigned long long and compared
                            numerically. You can't do this from the javascript language itself, that
                            requires pointers (direct memory addressing) (not to mention long long
                            datatypes), and I would be surprised if the engine actually takes this
                            approach.

                            take for example: reciprocity and reciprocate.

                            it would take the typical sort algorithm 9 loops to find 'a' vs 'i'. the
                            atypical algorithm described would take only 2. The atypical routine
                            "views" the raw data as:

                            0x7265636970726 f63 0x69747900...tr ash // '00' is end of string \0
                            and
                            0x7265636970726 f63 0x61746500...tr ash

                            for case-insensitve, you can bitwise | 0x2020202020202 020
                            if "last word" is not exactly 8 bytes long, the extra bytes should be
                            zeroed/cleared in case of = entries.

                            in MORE than 75% of the time, the atypical algorithm will find a
                            difference on the first comparison.

                            [AFAIK I am the inventor of this comparison algorithm... approx. 10 or
                            so years ago when 64-bit integer support became available on Macs...now
                            that doesn't mean that others might have developed the same or similar
                            on *their* own and I wouldn't believe it if I were the ONLY one to come
                            up with this -- but I doubt it is in use in the JS engine -- and upon
                            "cursory" checking, that appears to be the case]

                            In C, where one has low-level access to the CPU and direct memory
                            access, the algorithms in use are easily overridden and/or customized.
                            Since this access is not available through JavaScript, the algorithms in
                            place do not really concern me as I am not likely to be writing or
                            improving any of them...ever. I don't have the time nor the inclination.

                            I have considerable background and experience on which to base my
                            conjecture... and most general purpose public domain sort algorithms are
                            of the "typical" type. Your statement makes it sound like you might
                            know better -- why didn't you enlighten us as to which kind of algorithm
                            *is* used?


                            [color=blue]
                            >[color=green]
                            >>
                            >> [but this only matters if the operations are "time-critical"]
                            >>
                            >> oh... that little YYYYMMDD integer format -- it's called a "packed"
                            >> date format (packing integers is a "time-honored programming
                            >> tradition") -- been around for considerably longer than JavaScript.
                            >> Technically, the "digits" should be hexadecimal, but for sorting
                            >> purposes, decimal digits work just as well with the extra added
                            >> benefit of being easily readable in human terms.[/color]
                            >
                            >
                            > So you know some other names for that format - bravo.[/color]

                            This isn't "special" or even "arcane" knowledge. And "that format" is
                            not meant for representing information to humans (it's not really ANY
                            "format" - packing can take any arrangement) -- it is used only in
                            programming for data storage/manipulation.

                            Packing data is not language specific -- nor is it specific to dates. It
                            is, and has been for a very long time, a useful programming "tool." It
                            is used in data compression algorithms. One application of packed data
                            you SHOULD know about is RGB or HTML color representation: #CC9933 -- CC
                            is the red color component, 99 the green color component, and 33 the
                            blue color component. Using "integers" to store more than one piece of
                            datum is considered "packing." [packing does not really require integers
                            -- any block of memory will do -- longints, arrays, etc...even just
                            simple bytes.]


                            [color=blue]
                            > I made no
                            > assertion that it was peculiar to JavaScript - I know it isn't.
                            >
                            > I suggested the ISO standard format since it is an international
                            > standard that is unambiguous and widely understood and therefore very
                            > well suited for the web. It also sorts effortlessly and therefore is
                            > likely suitable for this and many other purposes.[/color]

                            All I'm saying is: if you have a considerable number of dates, all
                            within a narrow span of time, it is worth the effort to convert to a
                            number and use subtraction to make the comparison. In terms of
                            programming, it is usually MORE useful to keep the date in integer
                            (number) format, and use conversion to string for display instead of
                            vice versa... Make sense? ISO date format makes going from packed date
                            to string very easy.[color=blue]
                            >
                            > The OP may think it's a load of crap and totally ignore everything I
                            > posted - ain't life grand.[/color]

                            granted...

                            [color=blue]
                            >
                            >[/color]

                            Comment

                            • fox

                              #15
                              Re: sorting dates



                              Dr John Stockton wrote:[color=blue]
                              > JRS: In article <dccq76$22i$1@n ews.datasync.co m>, dated Fri, 29 Jul
                              > 2005 03:43:07, seen in news:comp.lang. javascript, fox
                              > <spamtrap@fxmah oney.com> posted :
                              >[color=green]
                              >>
                              >>comparing strings no doubt takes longer than comparing numbers.[/color]
                              >
                              >
                              > Perhaps so. But the comparison operator should be implemented at the
                              > ASM level or similar;[/color]

                              Not relevant -- no access to asm level in js.
                              [color=blue]
                              > so, for strings of the length in question, ISTM
                              > reasonably likely that the overall time will be dominated by other parts
                              > of the routine. If it matters, it should be tested.[/color]

                              i doubt it matters much in JS...
                              [color=blue]
                              >
                              > With 8-character strings, using the quickest test loop I know, I find
                              > the loop for comparison of equal 8-character Strings to be about 10%
                              > slower than that for the corresponding Numbers, loop overhead being
                              > about 20%. Other browsers are likely to differ.[/color]

                              not relevant... you didn't "get it"... and you "convenient ly" cut off "I
                              used to do it in C"! This can't be done in JS... you wasted your time
                              "testing" this in JS... at the "engine level" of JS's sort routine is
                              STILL the character by character comparison (I checked) and whether you
                              chop the string in sections of 8 or not, you still have string data types.
                              [color=blue]
                              >
                              >
                              >[color=green]
                              >>if all dates to be sorted are in YYYY-MM-DD format, and -- worst case,
                              >>they are all in the first week of the same year and month, then the
                              >>MINIMUM # of comparisons needed to be made to pass one as <> the other
                              >>would be 10 (one per character as long as they are equal) - two week
                              >>span, 9 -- etc... Unless, of course, JavaScript can compare "chunks" of
                              >>strings in one "throw" (I used to do it in C -- up to 8 characters at a
                              >>time -- typecast to longints -- really good way to speed up searches too)[/color]
                              >
                              >
                              > IIRC, the PC CPU instruction set provides for efficient comparisons of
                              > strings of 8-bit characters, and may do so, intentionally or otherwise,
                              > foe 16-bit ones.
                              >[/color]
                              yes... registers are loaded in 1 clock -- up to 64 bits on "modern"
                              machines... so why not 64 bits worth of characters in one instruction?
                              It's just bits...think of your basic character set as base256 numbers
                              and each character a digit. (Whether of not there is a human readable
                              glyph for each value doesn't make any difference to a computer.)[color=blue]
                              >
                              >[color=green]
                              >>oh... that little YYYYMMDD integer format -- it's called a "packed" date
                              >>format (packing integers is a "time-honored programming tradition") --
                              >>been around for considerably longer than JavaScript. Technically, the
                              >>"digits" should be hexadecimal, but for sorting purposes, decimal digits
                              >>work just as well with the extra added benefit of being easily readable
                              >>in human terms.[/color]
                              >
                              >
                              > It's not rightly called "packed". When discussing ISO 8601 formats, one
                              > should use ISO 8601 terminology.[/color]

                              I wasn't talking about iso date formats... so... not relevant.

                              Packed is NOT an ISO term -- it is a programmer's term for loading
                              multiple data into allocated memory, usually integer types (but chars,
                              arrays, and others can be used as well) -- data compression, if you will.

                              RGBColor and/or HTMLColor can also be referred to as packed color data.
                              [color=blue]
                              >
                              > The string 'YYYYMMDD' is "Basic format".
                              > The string 'YYYY-MM-DD' is "Extended format".
                              >
                              > A Basic format string can (with unary +) be converted to a javascript
                              > Number; but that is an IEEE Double, not an integer.[/color]


                              Number "type" is not relevant (nor is the *value* of the number
                              relevant: 0x20050730 would still yield the same result [but limited to
                              the next 5994 years.])

                              The number is just a scalar which should compare faster than the
                              strings. Relative magnitude is all that is necessary. The fact that
                              their "human readable" appearance "coincides" with an ISO date format is
                              inconsequential but convenient. The number used would be arranged in the
                              same order whether or not the iso standard existed.

                              [color=blue]
                              > Numbers in
                              > javascript do not have decimal digits.
                              >[/color]

                              LOL...

                              a couple possible responses:

                              1) What *possible* purpose does this statement serve?!?

                              and

                              2) What kind of digits DO Numbers have? fingers? toes? snorks?


                              D






                              Comment

                              Working...