Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 03-22-2012, 08:48 AM   PM User | #1
bizkit1
New Coder

 
Join Date: Oct 2011
Posts: 11
Thanks: 0
Thanked 0 Times in 0 Posts
bizkit1 is an unknown quantity at this point
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
bizkit1 is offline   Reply With Quote
Old 03-22-2012, 09:04 AM   PM User | #2
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,044
Thanks: 197
Thanked 2,412 Times in 2,390 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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.
__________________

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.

Last edited by Philip M; 03-22-2012 at 09:37 AM..
Philip M is offline   Reply With Quote
Old 03-22-2012, 09:33 AM   PM User | #3
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,465
Thanks: 0
Thanked 499 Times in 491 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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;
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/

Last edited by felgall; 03-22-2012 at 09:36 AM..
felgall is offline   Reply With Quote
Old 03-22-2012, 11:35 AM   PM User | #4
bizkit1
New Coder

 
Join Date: Oct 2011
Posts: 11
Thanks: 0
Thanked 0 Times in 0 Posts
bizkit1 is an unknown quantity at this point
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..
bizkit1 is offline   Reply With Quote
Old 03-23-2012, 09:54 AM   PM User | #5
bizkit1
New Coder

 
Join Date: Oct 2011
Posts: 11
Thanks: 0
Thanked 0 Times in 0 Posts
bizkit1 is an unknown quantity at this point
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?
bizkit1 is offline   Reply With Quote
Old 03-24-2012, 01:44 AM   PM User | #6
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,237
Thanks: 59
Thanked 3,998 Times in 3,967 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
Old Pedant is offline   Reply With Quote
Old 03-24-2012, 06:49 AM   PM User | #7
bizkit1
New Coder

 
Join Date: Oct 2011
Posts: 11
Thanks: 0
Thanked 0 Times in 0 Posts
bizkit1 is an unknown quantity at this point
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?
bizkit1 is offline   Reply With Quote
Old 03-24-2012, 07:38 AM   PM User | #8
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,237
Thanks: 59
Thanked 3,998 Times in 3,967 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
Old Pedant is offline   Reply With Quote
Old 03-24-2012, 09:00 AM   PM User | #9
bizkit1
New Coder

 
Join Date: Oct 2011
Posts: 11
Thanks: 0
Thanked 0 Times in 0 Posts
bizkit1 is an unknown quantity at this point
You're my hero
Thanks a lot!
bizkit1 is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 03:05 PM.


Advertisement
Log in to turn off these ads.