问题
I am developing a web-based application to capture start time and end time from system date-time but my main problem is that I don't know how can I get the duration time, between start and end time for downtime.
//Function to get current start time
var startTime = setInterval(function () { start() }, 1000);
function start() {
var startDate = new Date();
var timeStart = startDate.toLocaleTimeString();
$("#setCount").html(timeStart);
}
回答1:
Do you mean this:
var date1 = new Date();
var date2 = new Date();
var diff = date2 - date1; //milliseconds interval
upd
check JSFiddle
回答2:
Update:
If you want to display the time difference to user, Serigo's method will do it. But if it is for any development purposes, below functions will make your life easy.
Just wanted to let you know about this console utility functions.
Put this line in top of your app initialization code console.time('appLifeTime');
Put this one in where ever you feel that your app ends. console.timeEnd('appLifeTime');
console.time('appLifeTime');
setTimeout(function delay(){
console.timeEnd('appLifeTime');
}, 1500);
The above code piece will print, appLifeTime: 1500.583ms
.
AFAIK, console.time & console.timeEnd
works in firefox(with firebug) & webkit browsers(chrome, safari).
回答3:
To simply measure time elapsed, use Date.getTime()
which outputs current time in milliseconds since unix epoch.
You can substract one millis value from another to get the duration.
Example:
var startTime = new Date().getTime();
setTimeout(function () {
var endTime = new Date().getTime();
console.log("duration [ms] = " + (endTime-startTime));
}, 1500);
Output would be, of course: duration [ms] = 1500
(or couple ms less or more).
回答4:
I have this function to show the time distance between two dates:
export const timeDistance = (date1, date2) => {
let distance = Math.abs(date1 - date2);
const hours = Math.floor(distance / 3600000);
distance -= hours * 3600000;
const minutes = Math.floor(distance / 60000);
distance -= minutes * 60000;
const seconds = Math.floor(distance / 1000);
return `${hours}:${('0' + minutes).slice(-2)}:${('0' + seconds).slice(-2)}`;
};
The output in the format h:mm:ss
hours can grow arbitrary.
回答5:
Use this nifty jQuery plugin: http://timeago.yarp.com/
Timeago is a jQuery plugin that makes it easy to support automatically updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago"). Download, view the examples, and enjoy.
You opened this page about a minute ago. (This will update every minute. Wait for it.)
This page was last modified 13 days ago.
Ryan was born 34 years ago.
来源:https://stackoverflow.com/questions/15493521/how-do-i-calculate-a-duration-time