java script difference between two dates

Dear gurus,
I have 4 text boxes:  
1) date1 (user will fill)
2) date 2 (user will fill)
3) difference in years
4) difference in months

user will enter date1 and date 2. when click on submit, need to find difference between date1 and date2 and fill the result in 3rd, 4th text boxes.  3rd text box will have difference in years and forth text box will have difference in months. Date format that user fills is in: mm/dd/yyyy.

i need to write a javascript function for this. can anyone please help me?
LVL 1
Sri10Asked:
Who is Participating?
 
RobinSoftware EngineerCommented:
How about this?:

<script>
function doCalc()
{
  var strDate1 = document.frmDate.fldDate1.value;
  var strDate2 = document.frmDate.fldDate2.value;
  datDate1= Date.parse(strDate1);
  datDate2= Date.parse(strDate2);
  datediff = (datDate2-datDate1);
  var num_years = datediff/31536000000;
  var num_months = (datediff % 31536000000)/2628000000;
  document.frmDate.fldDiffY.value=num_years;
  document.frmDate.fldDiffM.value=num_months;
}
</script>
 
<form name=frmDate>
Date 1 :<input type=text name=fldDate1> (mm/dd/yyyy)<br>
Date 2 :<input type=text name=fldDate2> (mm/dd/yyyy)<br>
Diff. in years :<input type=text name=fldDiffY><br>
Diff. in months :<input type=text name=fldDiffM><br>
<input type=button value="Calc." onClick="doCalc()">
</form>
 
</body></html>

Open in new window

0
 
HonorGodSoftware EngineerCommented:
Something like this perhaps?
<!doctype html public '-//W3C//DTD HTML 4.01//EN' 'http://www.w3.org/TR/html4/strict.dtd'>
<html>
<head>
<title>Datediff</title>
<script type='text/javascript' src='../objDisplay.js'></script>
<script type='text/javascript'>
  function CalculateDiff( d1, d2 ) {
    var date1 = new Date( document.getElementById( d1 ).value );
    var date2 = new Date( document.getElementById( d2 ).value );
    if ( date1 > date2 ) {
      var tmp = date1;
      date1 = date2
      date2 = tmp;
    }
    var diff   = date2.getTime() - date1.getTime();
    var delta  = Math.ceil( diff / 86400000 );
    var days   = date2.getDate()     - date1.getDate();
    var months = date2.getMonth()    - date1.getMonth();
    var years  = date2.getFullYear() - date1.getFullYear();
    if ( days < 0 ) {
      //--------------------------------------------------------------
      // How many Days In Month (dim) for current month?
      //--------------------------------------------------------------
      var dim = new Date( date1.getFullYear(), date1.getMonth() + 1, 0 ).getDate();
      days = ( dim - days ) + date2.getDate();
      months--;
    }
    if ( months < 0 ) {
      months += 12;
      years--;
    }
 
      document.getElementById( 'Delta'  ).firstChild.nodeValue = delta;
      document.getElementById( 'Days'   ).firstChild.nodeValue = days;
      document.getElementById( 'Months' ).firstChild.nodeValue = months;
      document.getElementById( 'Years'  ).firstChild.nodeValue = years;
  }
</script>
</head>
<body>
<form name='f1' action=''>
  <br>Date 1 <input type='text' value='11/01/2006' id='Date1'/>
  <br>Date 2 <input type='text' value='12/29/2007' id='Date2'/>
<br>
  <input type='button' value='Calculate difference' onclick='CalculateDiff("Date1","Date2");'>
<br> Calculated Difference
  <table border='1'>
    <tr>  
      <th>Delta</th><td id='Delta'  align='center'>&nbsp;&nbsp;&nbsp;</td>
    </tr>  
    <tr>  
      <th>Days </th><td id='Days'   align='center'>&nbsp;&nbsp;&nbsp;</td>
    </tr>  
    <tr>  
      <th>Month</th><td id='Months' align='center'>&nbsp;&nbsp;&nbsp;</td>
    </tr>  
    <tr>  
      <th>Years</th><td id='Years'  align='center'>&nbsp;&nbsp;&nbsp;</td>
    </tr>  
  </table>
</form>
</body>
</html>

Open in new window

0
 
HonorGodSoftware EngineerCommented:
Interesting, you forced me to relook at this code (thank you for that).
I found some mistakes... :-(

Given a specific # of days, what value do you want to compute the number of months?

Say that the difference is 364 days, which is just under a year.
Do we do Math.floor( days / 30 ) ?
Is that close enough?

Or, should we divide the #days by 30.4375 (which is 365.25 days by 12, which should give us a closer approximation to the average number of days in a month)?
0
 
HonorGodSoftware EngineerCommented:
Thanks for the grade & points.

Here is the corrected/modified code
<!doctype html public '-//W3C//DTD HTML 4.01//EN' 'http://www.w3.org/TR/html4/strict.dtd'>
<html>
<head>
<title>Datediff</title>
<script type='text/javascript' src='../objDisplay.js'></script>
<script type='text/javascript'>
  var msPerSec  = 1000                           // # milliseconds / Second
  var secPerMin = 60                             // # Seconds / Minute
  var secPerHr  = 60     * secPerMin             // # Seconds / Hour
  var secPerDay = 24     * secPerHr              // # Seconds / Day
  var secPerYr  = 365.25 * secPerDay             // # Seconds / Year
 
  function field( id ) {
    var ele = document.getElementById( id )
    if ( !ele ) {
      alert( 'Element not found.  id="' + id + '"' )
    }
    return ele
  }
 
  function setVal( id, val ) {
    var ele = field( id )
    if ( ele ) {
      ele.innerHTML = val
    }
  }
 
  function getVal( id ) {
    var ele = field( id )
    var result = null
    if ( ele ) {
      result = ele.value
    }
    return result
  }
 
  function CalculateDiff( d1, d2 ) {
    var date1  = new Date( getVal( d1 ) )
    var date2  = new Date( getVal( d2 ) )
    var diff   = Math.floor( Math.abs( date2 - date1 ) / msPerSec )
    setVal( 'Delta', diff  )
    var years  = Math.floor( diff / secPerYr )
    setVal( 'Years', years )
    var rest   = diff - years * secPerYr
    var days   = Math.floor( rest / secPerDay )
    setVal( 'Days' , days  )
        rest   = rest - days * secPerDay
    var hours  = Math.floor( rest / secPerHr )
        rest   = rest - hours * secPerHr
    var mins   = Math.floor( rest / secPerMin )
        rest   = rest - mins * secPerMin
    setVal( 'Sec'  , rest  )
 
 
  }
</script>
</head>
<body>
<form name='f1' action=''>
  <br>Date 1 <input type='text' value='11/01/2006' id='Date1'/>
  <br>Date 2 <input type='text' value='12/29/2007' id='Date2'/>
<br>
  <input type='button' value='Calculate difference' onclick='CalculateDiff("Date1","Date2");'>
<br> Calculated Difference
  <table border='1'>
    <tr>
      <th>Delta</th><td id='Delta'  align='center'>&nbsp;&nbsp;&nbsp;</td>
    </tr>
    <tr>
      <th>Years</th><td id='Years'  align='center'>&nbsp;&nbsp;&nbsp;</td>
    </tr>
    <tr>
      <th>Days </th><td id='Days'   align='center'>&nbsp;&nbsp;&nbsp;</td>
    </tr>
    <tr>
      <th>Sec</th><td id='Sec' align='center'>&nbsp;&nbsp;&nbsp;</td>
    </tr>
  </table>
</form>
</body>
</html>

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.