javascript - time counter since start date and time

坚强是说给别人听的谎言 提交于 2019-11-29 05:19:15

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)!

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);
kravits88

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

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