Search code examples
jquerydatejs

sum input values using datejs


I am trying to grab input fields values, convert them to milliseconds, sum them all.

How can I sum hours using datejs ?

eg.

<input type="text" class="singleSumma" value="03:30">
<input type="text" class="singleSumma" value="02:30">
<input type="text" class="singleSumma" value="03:45">

<script type="text/javascript">
$(document).ready(function(){
    $(".singleSumma").each( function(){ 
        var singleSummaVal= $(this).val();              
             if (singleSummaVal) {                                      
                var ssv = Date.parse(singleSummaVal).getTime();
                           //how to sum input values using datejs?
                           // result= ssv.add(ssv);                         


            }           
    }); 
});
</script>

Solution by geoffrey.mcgill

var t = Date.today();
var sum= 0 ;

$(".singleSumma").each(function() {             
    var singleSummaVal = $(this).val();
       if (singleSummaVal) {
        var ssv = Date.parse(singleSummaVal);
        sum += (ssv - t);
            var ts = new TimeSpan(sum);

           console.log(ts.hours + ":" + ts.minutes);
      }
});

Solution

  • You have to get the value in milliseconds for each value from the start of the Day. Then add all those millisecond values together and pass into a new TimeSpan object. The TimeSpan will then calculate the number of days, hours, minutes, seconds and milliseconds.

    The following sample demonstrates the entire scenario.

    Example

    var d1 = Date.parse('03:30'),
        d2 = Date.parse('02:30'),
        d3 = Date.parse('03:45'),
        t = Date.today();
    
    var sum = (d1 - t) + (d2 - t) + (d3 - t);
    
    var ts = new TimeSpan(sum);
    
    console.log('hours', ts.hours); // 9
    console.log('minutes', ts.minutes); // 45
    

    Hope this helps.