InTry
InTry

Reputation: 1169

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);
      }
});

Upvotes: 1

Views: 210

Answers (2)

retype
retype

Reputation: 2385

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.

Upvotes: 1

Ladislav Zigo
Ladislav Zigo

Reputation: 514

Try use this

<script type="text/javascript">
$(document).ready(function(){
    var totalSum = 0;
    $(".singleSumma").each( function(){ 
        var singleSummaVal= $(this).val();              
            if (singleSummaVal) {                                       
                var ssv = Date.parse(singleSummaVal).getTime();
                totalSum += ssv; 
            }           
    }); 
    alert('ts in seconds' + totalSum ); 
    // or if you like other time properties
    var sumDT = new Date();
    sumDT.setTime(totalSum);    
});
</script>

Upvotes: 0

Related Questions