javascript - time counter since start date and time

前端 未结 3 802
南方客
南方客 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: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);

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

提交回复
热议问题