天之间的时差

时间:2012-12-27 11:36:17

标签: javascript time google-closure

  

可能重复:
  Difference between dates in JavaScript

我发现自己身处javascript砖墙。

我想在两个不同的日子里找到两次之间的差异(小时和分钟)。

我可以为每个产生小时,分钟和星期几,但无法确定如何实现一个功能,该功能将检查下一次有多长时间。

示例:

如果是星期五的16:00,下一次是星期一的13:00,那么输出将是69小时0分钟。

有人对如何最好地实现这个有任何想法吗?

N.B。我大量使用Google Closure。

2 个答案:

答案 0 :(得分:1)

var yourTimeStart = 'Friday 16:00'; //Your input
var yourTimeStop = 'Monday 13:00'; //Your input


var days = Array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");

var differenceDays = days.indexOf(yourTimeStop.split(" ")[0]) - days.indexOf(yourTimeStart.split(" ")[0]);
if (days.indexOf(yourTimeStart.split(" ")[0]) > days.indexOf(yourTimeStop.split(" ")[0])) differenceDays = differenceDays + 7;

var timeStart = yourTimeStart.split(" ")[1];
var timeStop = yourTimeStop.split(" ")[1];

var differenceHours = timeStop.split(":")[0] - timeStart.split(":")[0];
var differenceMins = timeStop.split(":")[1] - timeStart.split(":")[1]

var resultHours = differenceDays*24 + differenceHours;;


if (differenceMins < 0) {
    resultHours--;
    differenceMins = 60 + differenceMins; // differenceMins is negative
}

if (resultHours < 0) resultHours = resultHours + 7*24; //(this is if a you calculate the time between for example Monday 16:00 and Monday 12:00)

document.write(resultHours + " hour(s) and " + differenceMins + " minutes."); //output

答案 1 :(得分:0)

例如:

var dte = new DateTime(2012, 12, 26,1,0,0);
var dte2 = new DateTime(2012, 12, 27, 18, 5, 0);

var totalHours = (int) dte2.Subtract(dte).TotalHours;
var totalMin = dte2.AddHours(-totalHours).Subtract(dte).TotalMinutes;


Console.WriteLine(totalHours.ToString());
Console.WriteLine(totalMin.ToString());