我想找出两个日期之间的区别.我试过这段代码,但它给了我错误的价值.我希望得到两个日期之间的总分钟数,所以我将小时数转换为分钟数并增加到分钟数.
var hourDiff = timeEnd - timeStart;
var diffHrs = Math.round((hourDiff % 86400000) / 3600000);
var diffMins = Math.round(((hourDiff % 86400000) % 3600000) / 60000);
diffMins = diffMins + (diffHrs * 60);
Run Code Online (Sandbox Code Playgroud)
这timeEnd是Mon Jan 01 2007 11:30:00 GMT+0530 (India Standard Time),
并且timeStart是Mon Jan 01 2007 11:00:00 GMT+0530 (India Standard Time).
在这里,如果我得到的小时差异1,它应该是0和我得到的分钟30是正确的.但是应该是几个小时0.我在这里做错了吗?
str*_*rah 22
试试这段代码(使用ms作为初始单位)
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}
Run Code Online (Sandbox Code Playgroud)
JSFiddle:http://jsfiddle.net/n2WgW/
尝试:
var diffHrs = Math.floor((hourDiff % 86400000) / 3600000);
Run Code Online (Sandbox Code Playgroud)
Math.round将0.5小时差四舍五入到1。您只想获取“小时”变量中的“完整”小时,是否使用以下命令从变量中删除所有分钟Math.floor()
| 归档时间: |
|
| 查看次数: |
40465 次 |
| 最近记录: |