Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 9 of 9
  1. #1
    New Coder
    Join Date
    Oct 2011
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Exclamation javascript date substraction

    hello i have this code:

    Code:

    Code:
    function buildMonthlyEntries() {
        var startDate = new Date(document.getElementById('startDate').value);
        var endDate = new Date(document.getElementById('endDate').value);
        if(startDate == "Invalid Date" || endDate == "Invalid Date") { return null; }
        var entryCount = endDate.getMonth() - startDate.getMonth();
        var monthlyEntries = document.getElementById('monthlyEntries');
        monthlyEntries.innerHTML = "";
        for(var i = 0; i < entryCount; i++) {
            var textElement = document.createElement('input');
            textElement.setAttribute('type', 'text');
            textElement.setAttribute('id', 'entry' + i);
            monthlyEntries.appendChild(textElement);
        }
        return null;
    }
    
    
    <div id="dateRange">
        <input type="text" id="startDate">
        <input type="text" id="endDate">
    </div>
    <div id="monthlyEntries"></div>
    <INPUT TYPE="button" NAME="button" Value="Click" onClick="buildMonthlyEntries()">
    It calculates the number of months between the 2 dates and generates the number of input filds equal to the number of months. The only problem is when i change the year. For example if i have start date 2012-03-22 and enddate 2013-04-22, instead of generating 13 input fields it only generates 1 field, because it only substracts months. How can i make this script also calculate corectly months even if year is changed? Thanks

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,015
    Thanks
    203
    Thanked 2,538 Times in 2,516 Posts
    Evaluate endYear minus StartYear, then increment monthlyEntries by 12 x that number. 2013-2012 = 1 so increment by 1 x 12 (months).

    If the number of months is inclusive:-
    Start 3/2012 End 5/2012: endMonth+1 - startMonth = 3 fields, March April May
    Start 11/2012 End 3/2013: endMonth+1 - StartMonth = -7, plus 12 (one year) = 5 fields

    var endDate = new Date(document.getElementById('endDate').value);
    Prefer not to use the same name for a Javascript variable and an HTML element.

    You need to check that the entered dates are valid (not 56th February).

    Quizmaster: A peak in the Andes was confirmed by an expedition in 2000 to be the source of which river?
    Contestant: The Nile.
    Last edited by Philip M; 03-22-2012 at 09:37 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #3
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Subtract one date from the other and save the result as a "date". What you will actually get if you (getFullYear() * 12) + getMonth() +1 from that result will be the number of months difference between the two dates (rounded down).

    Code:
    start_date = new Date(document.getElementById('startDate').value);
    end_date = new Date(document.getElementById('endDate').value);
    diff = new Date();
    diff = end_date - start_date;
    entryCount = (diff.getFullYear() * 12) + diff.getMonth() + 1;
    Last edited by felgall; 03-22-2012 at 09:36 AM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #4
    New Coder
    Join Date
    Oct 2011
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts
    thank you, but i have a problem putting it all together:

    Code:
    function buildMonthlyEntries() {
        var startDate = new Date(document.getElementById('datastart').value);
        var endDate = new Date(document.getElementById('dataend').value);
        diff = new Date();
        diff = endDate - startDate;
        if(startDate == "Invalid Date" || endDate == "Invalid Date") { return null; }
        var entryCount = (diff.getFullYear() * 12) + diff.getMonth() + 1;
        var monthlyEntries = document.getElementById('monthlyEntries');
    
        monthlyEntries.innerHTML = "";
        for(var i = 0; i < entryCount; i++) {
            var textElement = document.createElement('input');
            textElement.setAttribute('type', 'text');
            textElement.setAttribute('id', 'entry' + i);
    
            monthlyEntries.appendChild(textElement);
            
        }
    
        return null;
    }
    can you please help me with this one? because i am new to javascript
    Last edited by bizkit1; 03-22-2012 at 11:40 AM.

  • #5
    New Coder
    Join Date
    Oct 2011
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts
    ok i managed to make it work:

    Code:
    function buildMonthlyEntries() {
        var startDate = new Date(document.getElementById('datastart').value);
        var endDate = new Date(document.getElementById('dataend').value);
        if(startDate == "Invalid Date" || endDate == "Invalid Date") { return null; }
        var entryCount = (endDate.getMonth() - startDate.getMonth())+(endDate.getFullYear() - startDate.getFullYear())*12;
        var monthlyEntries = document.getElementById('monthlyEntries');
        monthlyEntries.innerHTML = "";
        for(var i = 0; i < entryCount; i++) {
            var textElement = document.createElement('input');
            textElement.setAttribute('type', 'text');
            textElement.setAttribute('name', 'entry[]');
            monthlyEntries.appendChild(textElement);
    
        }
        return null;
    }
    But would it be posible to add in front of every generated input field the month name?

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,519
    Thanks
    77
    Thanked 4,381 Times in 4,346 Posts
    Can I suggest an entirely different way?
    Code:
    // user full month names if you prefer
    var monthNames = [ "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" ];
    
    function buildMonthlyEntries() {
        var startDate = new Date(document.getElementById('datastart').value);
        var endDate = new Date(document.getElementById('dataend').value);
        if(startDate == "Invalid Date" || endDate == "Invalid Date") { return null; }
    
        var monthlyEntries = document.getElementById('monthlyEntries');
        monthlyEntries.innerHTML = "";
    
        // uncomment next line if you want the loop to be INCLUSIVE of the endDate:
        // endDate.setMonth( endDate.getMonth() + 1 );
    
        // start with startDate; loop until we reach endDate
        for( var dt = startDate; 
               ! ( dt.getFullYear() == endDate.getFullYear() && dt.getMonth() == endDate.getMonth() );  
               dt.setMonth( dt.getMonth() + 1 )
        ) {
            monthlyEntries.append( document.createTextNode(
                      monthNames(dt.getMonth()) + " " + String(dt.getFullYear()).substring(2)
                  );
            var textElement = document.createElement('input');
            textElement.setAttribute('type', 'text');
            textElement.setAttribute('name', 'entry[]');
            monthlyEntries.appendChild(textElement);
        }
        return null;
    }
    See? Why count the months. Just keep bumping the date until you reach the endDate.

    The loop as given will be exclusive of the endDate. If you want it to be inclusive, just uncomment the indicated line.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #7
    New Coder
    Join Date
    Oct 2011
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts
    thank you for your reply, i copied the code but it doesn`t seem to work, it does not generate inputs anymore. Maybe i`m missing something?

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,519
    Thanks
    77
    Thanked 4,381 Times in 4,346 Posts
    Sorry. A couple of typos. Easy to find with any debugger.

    This is tested and works, now:
    Code:
    // user full month names if you prefer
    var monthNames = [ "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" ];
    
    function buildMonthlyEntries() {
        var startDate = new Date(document.getElementById('datastart').value);
        var endDate = new Date(document.getElementById('dataend').value);
        if(startDate == "Invalid Date" || endDate == "Invalid Date") { return null; }
    
        var monthlyEntries = document.getElementById('monthlyEntries');
        monthlyEntries.innerHTML = "";
    
        // uncomment next line if you want the loop to be INCLUSIVE of the endDate:
        // endDate.setMonth( endDate.getMonth() + 1 );
    
        // start with startDate; loop until we reach endDate
        for( var dt = startDate; 
               ! ( dt.getFullYear() == endDate.getFullYear() && dt.getMonth() == endDate.getMonth() );  
               dt.setMonth( dt.getMonth() + 1 )
        ) {
            monthlyEntries.appendChild( document.createTextNode(
                      monthNames[dt.getMonth()] + " " + String(dt.getFullYear()).substring(2)
                  ) );
            var textElement = document.createElement('input');
            textElement.setAttribute('type', 'text');
            textElement.setAttribute('name', 'entry[]');
            monthlyEntries.appendChild(textElement);
            // next line optional...may or may not need it depending on your CSS
            monthlyEntries.appendChild(document.createElement("br"));
        }
        return null;
    }
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #9
    New Coder
    Join Date
    Oct 2011
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts
    You're my hero
    Thanks a lot!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •