Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

javascript - How can I make a program that reads the date(hour,minutes,seconds) then it subtracts it from the second date

I have a task to create a program where the user gives the Hour, Minute, Second, then he gives another Hour, Minute, Second then the program should substract the second date from the first one.

I have been trying to not use the date format, but I can't get it to work.

The date has to be in a 24h format, and these two dates have to be in the same day. So if I write 12:59:59 then I couldn't set the second date to 12:59:58 just 13:00:00.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is an approach how i would do it.

var hours1, mins1, secs1, hours2, mins2, secs2;

/**
 * get html element by id.
 * @param {string} id give the html element id 
 * @return {object} document.getElementById(id);
 */
function GetId(id) { return document.getElementById(id) }

function subDate() {
    hours1 = GetId("hours1").value;
    mins1 = GetId("mins1").value;
    secs1 = GetId("secs1").value;
    hours2 = GetId("hours2").value;
    mins2 = GetId("mins2").value;
    secs2 = GetId("secs2").value;
    
    // Set times to seconts
    let time1 = ((mins1 * 60) + (hours1 * 3600)) + Number(secs1),
        time2 = ((mins2 * 60) + (hours2 * 3600)) + Number(secs2);
       
    let hours = 0,
        mins = 0, 
        // Subtract all seconds. 
        secs = time2 - time1;
    
    // Count all hours
    while (secs >= 3600) {
      hours +=1 ;
      secs -= 3600;
    }
    
    // Count all mins
    while (secs >= 60) {
      mins += 1;
      secs -= 60;
    }
    
    // Show anwser
    let html = GetId("ans");
    html.innerHTML = hours + ":" + mins + ":" + secs;
}
<p>
<input type="number" id="hours1" value="0" min="0" max="24">:
<input type="number" id="mins1" value="0" min="0" max="59">:
<input type="number" id="secs1" value="0" min="0" max="59">
</p>
<p>
<input type="number" id="hours2" value="0" min="0" max="24">:
<input type="number" id="mins2" value="0" min="0" max="59">:
<input type="number" id="secs2" value="0" min="0" max="59">
</p>

<button onclick="subDate()">Sup dates</button>

<p id="ans"></p>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...