counting years between two dates

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

    counting years between two dates

    Hello all

    Problem like in subject. There is no problem when I want to count days
    between two dates. Problem is when I want to count years becouse of
    leap years.

    For ex.

    between
    2002-11-19 2003-11-19
    365 days = 1 year

    between
    2003-11-19 2004-11-19
    366 days = 1 year (leap)

    Thanks
    Bambero
  • news.west.cox.net

    #2
    Re: counting years between two dates

    > Problem like in subject. There is no problem when I want to count days[color=blue]
    > between two dates. Problem is when I want to count years becouse of
    > leap years.
    >
    > For ex.
    >
    > between
    > 2002-11-19 2003-11-19
    > 365 days = 1 year
    >
    > between
    > 2003-11-19 2004-11-19
    > 366 days = 1 year (leap)
    >[/color]

    I am not familiar enough with javascript to be able to give you the correct
    answer, but I can tell you that you will need to use some sort of date
    object.

    The date object should have a way of finding the date as it is represented
    in seconds since the epoch.

    So, you would create two date objects, find their time in seconds since
    the epoch, and convert this into a number of days.

    In fact I just googled for "javascript date" and the first result has the
    answer.

    // UNTESTED
    var date1 = new Date(yr_num, mo_num, day_num);
    var date2 = new Date(yr_num2, mo_num2, day_num2);

    var date1_in_second s = date1.parse();
    var date2_in_second s = date2.parse();

    var difference = date_2_in_secon ds - date_1_in_secon ds
    // above is assuming date2 is more recent than date1

    //now difference is the number of seconds between the two dates so...
    var difference in years = int(difference / 140400)
    //this would be the number of days in between the two dates...


    Comment

    • Lee

      #3
      Re: counting years between two dates

      Bambero said:[color=blue]
      >
      >Hello all
      >
      >Problem like in subject. There is no problem when I want to count days
      >between two dates. Problem is when I want to count years becouse of
      >leap years.[/color]



      Comment

      • RobG

        #4
        Re: counting years between two dates

        Bambero wrote:[color=blue]
        > Hello all
        >
        > Problem like in subject. There is no problem when I want to count days
        > between two dates. Problem is when I want to count years becouse of
        > leap years.[/color]

        I would guess you are having trouble with months too.

        The best way is to convert to date objects, then deal with those. When
        measuring days, months and years between two dates it is simpest to
        add one year/month/day at a time until the earlier date gets to the
        later date. The following script doesn't care whether the lower date
        is entered first or last, it sorts them out anyway.

        The following assumes you have done all that is required to validate
        that dates are entered as yyyy-mm-dd. It is tested in Safari, but
        should work elsewhere.

        Have fun, Rob.


        <html><head><ti tle>Date fun</title>

        <script type="text/javascript">
        function check2k(a) {
        return (a<1900)?a -= -1900:a;
        }

        function addYr(a) {
        return new Date(check2k(1* a.getYear()+1), a.getMonth(),a. getDate());
        }

        function addMth(a) {
        return new Date(check2k(a. getYear()),1*a. getMonth()+1,a. getDate());
        }

        function addDay(a) {
        return new Date(check2k(a. getYear()),a.ge tMonth(),1*a.ge tDate()+1);
        }

        function doDate(in1,in2) {
        var x = in1.split('-'),
        y = in2.split('-'),
        yrCount = 0,
        mthCount = 0,
        dayCount = 0;

        // Convert to dates
        var date0 = new Date(x[0],x[1]-1,x[2]);
        var date1 = new Date(y[0],y[1]-1,y[2]);

        // Make the lower one date0
        if (date0 > date1) {
        date0 = date1;
        date1 = new Date(x[0],x[1]-1,x[2]);
        }

        // Add years to date0 until after date1
        while (addYr(date0) <= date1) {
        date0 = addYr(date0);
        yrCount++;
        }

        // Add months to date0 until after date1
        while (addMth(date0) <= date1) {
        date0 = addMth(date0);
        mthCount++;
        }

        // Add days to date0 until after date1
        while (addDay(date0) <= date1) {
        date0 = addDay(date0);
        dayCount++
        }

        alert('Years: ' + yrCount
        + '\nMonths: ' + mthCount
        + '\nDays: ' + dayCount
        );
        }
        </script>

        </head>
        <body>

        <form action="">
        <input type="text" name="y1" width="100px"
        value="2003-12-23">Year 1<br>
        <input type="text" name="y2" width="100px"
        value="2002-12-28">Year 2<br>
        <input type="button" value="Calc years" onclick="
        doDate(this.for m.y1.value, this.form.y2.va lue);
        "><br>
        </form>

        </body></html>

        Comment

        • RobG

          #5
          Re: counting years between two dates

          RobG wrote:
          [...][color=blue]
          > The following assumes you have done all that is required to validate
          > that dates are entered as yyyy-mm-dd. It is tested in Safari, but
          > should work elsewhere.[/color]
          [...]

          Forgot to mention, you also need to ensure dates are after 1900.

          Cheers, Rob.

          Comment

          • Dr John Stockton

            #6
            Re: counting years between two dates

            JRS: In article <99und.330977$a 85.63670@fed1re ad04>, dated Fri, 19 Nov
            2004 14:08:29, seen in news:comp.lang. javascript, news.west.cox.n et
            <sean.berry2@co x.net> posted :[color=blue][color=green]
            >> Problem like in subject.[/color][/color]

            NEVER rely on the Subject line.
            [color=blue]
            > There is no problem when I want to count days[color=green]
            >> between two dates. Problem is when I want to count years becouse of
            >> leap years.
            >>
            >> For ex.[/color][/color]

            Don't use abbreviations in languages which are not your own, unless you
            have good reason for believing that they exist and you know their exact
            meaning.
            [color=blue][color=green]
            >>
            >> between
            >> 2002-11-19 2003-11-19
            >> 365 days = 1 year[/color][/color]

            Actually there are 364 days between those dates; it is the difference
            which is 365.
            [color=blue][color=green]
            >> between
            >> 2003-11-19 2004-11-19
            >> 366 days = 1 year (leap)
            >>[/color]
            >
            >I am not familiar enough with javascript to be able to give you the correct
            >answer,[/color]

            Better, then, to leave it to those who do.
            [color=blue]
            > but I can tell you that you will need to use some sort of date
            >object.[/color]

            /Non sequitur/.

            [color=blue]
            >The date object should have a way of finding the date as it is represented
            >in seconds since the epoch.[/color]

            It is not represented in seconds.

            [color=blue]
            >So, you would create two date objects, find their time in seconds since
            >the epoch, and convert this into a number of days.[/color]

            One does not *need* two objects; it is possible to use one twice; or,
            for speed, not to use a date object at all. The best solution depends
            on the format in which the date is initially available. For example, if
            the dates are ISO 8601 YYYYMMDD strings, one can subtract them, divide
            by 1e4, and truncate.
            [color=blue]
            >In fact I just googled for "javascript date" and the first result has the
            >answer.[/color]

            Indiscriminate Googling for javascript is a *reliable* method of finding
            bad answers. A good answer could have been found by studying the FAQ of
            this newsgroup.
            [color=blue]
            >// UNTESTED[/color]

            Untested code, even when written by an expert, is almost reliably wrong.
            [color=blue]
            >var date1 = new Date(yr_num, mo_num, day_num);
            >var date2 = new Date(yr_num2, mo_num2, day_num2);
            >
            >var date1_in_second s = date1.parse();
            >var date2_in_second s = date2.parse();[/color]

            The date object does not AFAIK ever have a native parse method.
            [color=blue]
            >var difference = date_2_in_secon ds - date_1_in_secon ds
            >// above is assuming date2 is more recent than date1
            >
            >//now difference is the number of seconds between the two dates so...
            >var difference in years = int(difference / 140400)
            >//this would be the number of days in between the two dates...[/color]

            140400 seconds is one day fifteen hours; that is less than a year. As
            the OP evidently realises, the number of seconds in a year is not
            constant.

            Post only tested solutions, on topics that you have a good understanding
            of.


            A further problem, for methods based on seconds, would be shown (to
            many users) for the differences of some pairs of dates of the form
            YYYY-10-28.


            For the OP :

            X = (Y2-Y1) - (M2*100+D2 < M1*100+D1) // for Y M D numbers

            A1 = Y1.split(/\D+/) ; A2 = Y2.split(/\D+/)
            X = (A2[0]-A1[0]) - (A2[1]*100 + +A2[2] < A1[1]*100 + +A1[2])
            // for inputs YYYY-MM-DD, YYYY/MM/DD, etc.

            Lightly tested. 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

            • RobG

              #7
              Re: counting years between two dates

              Dr John Stockton wrote:
              [...][color=blue]
              > A further problem, for methods based on seconds, would be shown (to
              > many users) for the differences of some pairs of dates of the form
              > YYYY-10-28.[/color]

              What is the accepted value for 2004-02-29 + 1 year? Is it 2005-03-01
              as the JavaScript date function in every browser I tested returns, or
              is it 2005-02-28 as logic might have it (if my logic is consistent with
              popular opinion...)

              Cheers, Rob.

              Comment

              • Dr John Stockton

                #8
                Re: counting years between two dates

                JRS: In article <41a07bdc$0$257 62$5a62ac22@per-qv1-newsreader-
                01.iinet.net.au >, dated Sun, 21 Nov 2004 21:27:24, seen in
                news:comp.lang. javascript, RobG <rgqld@iinet.ne t.auau> posted :[color=blue]
                >Dr John Stockton wrote:
                >[...][color=green]
                >> A further problem, for methods based on seconds, would be shown (to
                >> many users) for the differences of some pairs of dates of the form
                >> YYYY-10-28.[/color]
                >
                > What is the accepted value for 2004-02-29 + 1 year? Is it 2005-03-01
                > as the JavaScript date function in every browser I tested returns, or
                > is it 2005-02-28 as logic might have it (if my logic is consistent with
                > popular opinion...)[/color]

                Note that I wrote YYYY-10-28.

                AFAICS, ECMA does not define (2004-02-29 + 1 year) explicitly; but it is
                probably implicitly defined as a consequence of the way that ECMA says
                that set[Full]Year should work; and likewise for adding a month to dates
                too late in the previous longer month.

                Note that D = new Date("2003/01/31") ; D.setMonth(1) gives March
                3rd, and that will not generally be acceptable.

                IMHO, the accepted value, outside javascript, is "Don't know; get a
                [signed] ruling from the Boss"; either Feb 28 xor Mar 1 should be
                considered acceptable. Somewhere on my site, IIRC, there is code to
                handle the case of incrementing by an integer number of months from a
                day-of-month not available at the destination ... js-date0.htm#MC .


                Those who can read German might like to look at
                <URL:http://www.merlyn.demo n.co.uk/zel-82px.htm>
                and its neighbours; those knowing Latin see 83 not 82.

                --
                © 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

                Working...