Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

time - Difference between two dates in minute, hours javascript

I want to find difference between two dates. I have tried this code but it gives me wrong values. I want get total minutes between two dates, so I am converting hours to minutes and adding to minutes.

var hourDiff = timeEnd - timeStart;
var diffHrs = Math.round((hourDiff % 86400000) / 3600000);
var diffMins = Math.round(((hourDiff % 86400000) % 3600000) / 60000);
diffMins = diffMins + (diffHrs * 60);

Here timeEnd is Mon Jan 01 2007 11:30:00 GMT+0530 (India Standard Time),

and timeStart is Mon Jan 01 2007 11:00:00 GMT+0530 (India Standard Time).

Here if hours difference I am getting 1, it should be 0 and minutes I am getting 30 that is right. But hours should be 0. Am I doing something wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this code (uses ms as initial units)

var timeStart = new Date("Mon Jan 01 2007 11:00:00 GMT+0530").getTime();
var timeEnd = new Date("Mon Jan 01 2007 11:30:00 GMT+0530").getTime();
var hourDiff = timeEnd - timeStart; //in ms
var secDiff = hourDiff / 1000; //in s
var minDiff = hourDiff / 60 / 1000; //in minutes
var hDiff = hourDiff / 3600 / 1000; //in hours
var humanReadable = {};
humanReadable.hours = Math.floor(hDiff);
humanReadable.minutes = minDiff - 60 * humanReadable.hours;
console.log(humanReadable); //{hours: 0, minutes: 30}

JSFiddle: http://jsfiddle.net/n2WgW/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...