简体   繁体   中英

Time to Seconds and Seconds to Time in Javascript

I have My Code below,

    Before=document.getElementsByName("beforehr[]");
    After=document.getElementsByName("afterhr[]");
    MonthTotal=0
    for(i=0;i<Before.length;i++){
        BeforeInSeconds= // Convert Before[i].value to Seconds
        AfterInSeconds= // Convert After[i].value to Seconds
        MonthTotal=parseInt(MonthTotal)+ parseInt(BeforeInSeconds)+parseInt(AfterInSeconds);

}
MonthTotalHRS= // Convert MonthTotal value to Time
document.getElementById("txtMonthTotal").value=MonthTotal;
document.getElementById("Mthtotal").innerHTML=MonthTotalHRS;

I need to convert the Before Hours to Seconds, After Hours to Seconds, sum All the Seconds and convert to Time and put it into Mthtotal

Assuming that variables Before and After are arrays.

 var Before = [1, 2]; //180 Secs var After = [3, 4]; // 420 Secs var MonthTotal=0; function secondsToHms(d) { // Function to convert Secs to H:m:s d = Number(d); var h = Math.floor(d / 3600); var m = Math.floor(d % 3600 / 60); var s = Math.floor(d % 3600 % 60); var hDisplay = h > 0 ? h + (h == 1 ? " hour " : " hours ") : ""; var mDisplay = m > 0 ? m + (m == 1 ? " minute " : " minutes ") : ""; var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : ""; return hDisplay + mDisplay + sDisplay; } for(i=0;i<Before.length;i++) { BeforeInSeconds= Before[i] * 60; AfterInSeconds= After[i] * 60; MonthTotal=parseInt(MonthTotal)+ parseInt(BeforeInSeconds)+parseInt(AfterInSeconds); } console.log(MonthTotal); //600 Secs var convertedop=secondsToHms(MonthTotal); alert(convertedop); 

You can use .split(':') to split up your time format into an array. Where index 0 is the hour, index 1 is the minutes and index 2 is the seconds. You can then convert each time unit into seconds.

Hours to seconds: hour*3600

Minutes to seconds: minutes*60

Seconds to seconds: seconds*1 so just seconds

Doing all of this will give you your total result:

 var before = [...document.getElementsByName("beforehr[]")]; var after = [...document.getElementsByName("afterhr[]")]; var monthTotal = 0 for (i = 0; i < before.length; i++) { var beforeTime = before[i].value.split(':'); var afterTime = after[i].value.split(':'); var hourSeconds = +beforeTime[0] * 3600; // Convert the hours to seconds var minuteSeconds = +beforeTime[1] * 60; // Convert the mins to secs var seconds = +beforeTime[2]; // No conversions needed for secs to secs var beforeInSeconds = hourSeconds + minuteSeconds + seconds; // The above can be compresed into one line. I'll repeat the above for the afterTime on one line as an example: var afterInSeconds = (+afterTime[0] * 3600) + (+afterTime[1] * 60) + (+afterTime[2]) monthTotal += parseInt(beforeInSeconds) + parseInt(afterInSeconds); } console.log("Month total in seconds", monthTotal) // Hours, minutes and seconds (round down) var hrs = ~~(monthTotal / 3600); var mins = ~~((monthTotal % 3600) / 60); var secs = ~~monthTotal % 60; console.log("Month total in H:M:S", hrs +':' +mins + ':' + secs); 
 <input type="text" value="1:0:0" name="beforehr[]" /> <input type="text" value="1:0:0" name="beforehr[]" /> <br /> <input type="text" value="4:0:0" name="afterhr[]" /> <input type="text" value="4:0:0" name="afterhr[]" /> 

Also, note the unary + operator is similar to parseInt (it acts a little differently however).

The ~~ is simply just a fancy way of saying Math.floor(number)

Solution Simplified

<script>
    function CalOt(){
        Before=document.getElementsByName("beforehr[]");
        After=document.getElementsByName("afterhr[]");
        TodayOt=document.getElementsByName("txtTodayOt[]");
        MonthTotal=0
        for(i=0;i<Before.length;i++){
            //alert(TimetoSec(Before[i].value));
            BeforeInSeconds=TimetoSec(Before[i].value); //Convert Before[i].value to Seconds
            AfterInSeconds=TimetoSec(After[i].value);//Convert After[i].value to Seconds
            Daytot=parseInt(BeforeInSeconds)+parseInt(AfterInSeconds);
            TodayOt[i].value=SecToTime(Daytot);
        MonthTotal=parseInt(MonthTotal)+parseFloat(Daytot);

}
MonthTotalHRS=SecToTime(MonthTotal);// Convert MonthTotal value to Time
document.getElementById("txtMonthTotal").value=MonthTotal;
document.getElementById("Mthtotal").innerHTML=MonthTotalHRS;
}
function TimetoSec(Time){
    TimeSplit=Time.split(":");
    HoursSeconds=TimeSplit[0]*60*60;
    Minutes=TimeSplit[1]*60;
    TotalSec=parseFloat(HoursSeconds)+parseFloat(Minutes)+parseFloat(TimeSplit[2]);
    console.log(TotalSec+"\n");
    return TotalSec;
}
function SecToTime(Seconds){
    Hr=Math.floor(Seconds/(60*60));
    Mn=Seconds % (60*60);
    Min=Math.floor(Mn/(60));
    Sec=Mn % (60);
    return Hr+":"+Min+":"+Sec;

}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM