javascript - time counter since start date and time

前端 未结 3 801
南方客
南方客 2020-12-17 05:35

I have a new business, where I just hired someone to work for me, I am trying to make it easy for her to track her time, so I created a clock in button, that creates a recor

相关标签:
3条回答
  • 2020-12-17 06:02

    Get the difference between two dates by subtracting them:

    var duration = end - start;
    

    This will give you the number of milliseconds between the dates. You can use the milliseconds to figure out hours, minutes, and seconds. Then it's just a matter of string manipulation and writing the value to the page. To update the timer once per second, use setInterval():

    setInterval(writeDuration, 1000);
    
    0 讨论(0)
  • 2020-12-17 06:06

    I would use momentJS fromNow function. You can get the time started as variable on page load then call fromNow on that and current time to get time between the two every time the clock is clicked:

    var StartedWorkDateTime = GetStartedTime();
    moment(StartedWorkDateTime).fromNow(true);
    

    Non momentJS:

    var date1 = new Date("7/11/2010 15:00");
    var date2 = new Date("7/11/2010 18:00");
    var timeDiff = Math.abs(date2.getTime() - date1.getTime());
    var diffHours = Math.ceil(timeDiff / (1000 * 3600)); 
    alert(diffHours);
    

    reference

    0 讨论(0)
  • 2020-12-17 06:25

    From your question I understand you store the date and time on start? So then you can use PHP to echo this information in a starting Date object and let a setInterval-function do the current timegetting and calculation of the time working.

    See working example here: http://jsfiddle.net/c0rxkhyz/1/

    This is the code:

    var startDateTime = new Date(2014,0,1,23,59,59,0); // YYYY (M-1) D H m s ms (start time and date from DB)
    var startStamp = startDateTime.getTime();
    
    var newDate = new Date();
    var newStamp = newDate.getTime();
    
    var timer; // for storing the interval (to stop or pause later if needed)
    
    function updateClock() {
        newDate = new Date();
        newStamp = newDate.getTime();
        var diff = Math.round((newStamp-startStamp)/1000);
        
        var d = Math.floor(diff/(24*60*60)); /* though I hope she won't be working for consecutive days :) */
        diff = diff-(d*24*60*60);
        var h = Math.floor(diff/(60*60));
        diff = diff-(h*60*60);
        var m = Math.floor(diff/(60));
        diff = diff-(m*60);
        var s = diff;
        
        document.getElementById("time-elapsed").innerHTML = d+" day(s), "+h+" hour(s), "+m+" minute(s), "+s+" second(s) working";
    }
    
    timer = setInterval(updateClock, 1000);
    <div id="time-elapsed"></div>

    Attention! The month number in the new Date() declaration is minus one (so January is 0, Feb 1, etc)!

    0 讨论(0)
提交回复
热议问题