public String timeDifference(String startTime, String leavedTime) {
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1;
String dd =null;
try {
date1 = format.parse(startTime);
Date date2 = format.parse(leavedTime);
long difference = date2.getTime() - date1.getTime();
long diffMinutes = difference / (60 * 1000) % 60;
long diffHours = difference / (60 * 60 * 1000) % 24;
dd=diffHours + " : " + diffMinutes ;
} catch (ParseException ex) {
System.out.println(ex);
}
return dd;
}
我想知道,
1)long diffMinutes = difference / (60 * 1000) % 60;
2) long diffHours = difference / (60 * 60 * 1000) % 24
在代码1中使用%60的目的是什么 在代码2中使用%24的目的是什么
有人能给我一个明确的解释吗?
答案 0 :(得分:1)
[TestFixture]
public static class MyTakeLastExtensions
{
/// <summary>
/// Intent: Returns the last N elements from an array.
/// </summary>
public static T[] MyTakeLast<T>(this T[] source, int n)
{
if (source == null)
{
throw new Exception("Source cannot be null.");
}
if (n < 0)
{
throw new Exception("Index must be positive.");
}
if (source.Length < n)
{
return source;
}
var result = new T[n];
int c = 0;
for (int i = source.Length - n; i < source.Length; i++)
{
result[c] = source[i];
c++;
}
return result;
}
[Test]
public static void MyTakeLast_Test()
{
int[] a = new[] {0, 1, 2};
{
var b = a.MyTakeLast(2);
Assert.True(b.Length == 2);
Assert.True(b[0] == 1);
Assert.True(b[1] == 2);
}
{
var b = a.MyTakeLast(3);
Assert.True(b.Length == 3);
Assert.True(b[0] == 0);
Assert.True(b[1] == 1);
Assert.True(b[2] == 2);
}
{
var b = a.MyTakeLast(4);
Assert.True(b.Length == 3);
Assert.True(b[0] == 0);
Assert.True(b[1] == 1);
Assert.True(b[2] == 2);
}
{
var b = a.MyTakeLast(1);
Assert.True(b.Length == 1);
Assert.True(b[0] == 2);
}
{
var b = a.MyTakeLast(0);
Assert.True(b.Length == 0);
}
{
Assert.Throws<Exception>(() => a.MyTakeLast(-1));
}
{
int[] b = null;
Assert.Throws<Exception>(() => b.MyTakeLast(-1));
}
}
}
运算符是模运算。在此代码中,%
将是时差内小时内的分钟数,diffMinutes
将是时差内的小时数。
除以diffHours
将原始差异(以毫秒为单位)转换为分钟单位(除以1000获得秒数,然后除以60获得分钟数。)
例如,如果时差为2天3小时52分钟,则(60 * 1000)
将为52,diffMinutes
将为3。
如果没有模数,结果会从“小时内> ”中的分钟数变为“经过的分钟总数”。例如,经过133分钟(没有模数)变为“一小时内13分钟”的模数。