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

荒凉一梦 提交于 2019-12-13 10:28:35

问题


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.


回答1:


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>



回答2:


    DateSubtraction = function( date1, date2 ) {

      // Convert both dates to milliseconds
      var date1_ms = date1.getTime();
      var date2_ms = date2.getTime();

      // Calculate the difference in milliseconds
      var difference_ms = date2_ms - date1_ms;
      console.log(difference_ms);
    }

    //Set the two dates
    var y2k  = new Date(2000, 0, 1); 
    var Jan1st2010 = new Date(y2k.getFullYear() + 10, y2k.getMonth(), y2k.getDate());
    var today= new Date();
    DateSubtraction(Jan1st2010, today);

You will have to modify for user input



来源:https://stackoverflow.com/questions/46973205/how-can-i-make-a-program-that-reads-the-datehour-minutes-seconds-then-it-subtr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!