public long compareTwoTimeStamps(Timestamp currentTime, Timestamp oldTime)
{
long milliseconds1 = oldTime.getTime();
long milliseconds2 = currentTime.getTime();
long diff = milliseconds2 - milliseconds1;
long diffMinutes = diff / (60 * 1000);
return diffMinutes;
}
上述代码也考虑了日期。 我需要比较时间戳的2个实例,并仅比较时间戳的时间部分。不应考虑日期。每当我比较它时,比较也会考虑日期。
答案 0 :(得分:2)
一个解决方案,在时间戳上使用getHours
,getMinutes
:
public long compareTwoTimeStamps(java.sql.Timestamp currentTime, java.sql.Timestamp oldTime)
{
long min1 = oldTime.getHours() * 60 + oldTime.getMinutes();
long min2 = currentTime.getHours() * 60 + currentTime.getMinutes();
return min2 - min1;
}
或没有任何弃用的方法:
public long compareTwoTimeStamps(java.sql.Timestamp currentTime, java.sql.Timestamp oldTime)
{
final Calendar oldCal = Calendar.getInstance();
oldCal.setTime(oldTime);
long min1 = oldCal.get(Calendar.HOUR) * 60 + oldCal.get(Calendar.MINUTE);
final Calendar currentCal = Calendar.getInstance();
oldCal.setTime(currentTime);
long min2 = currentCal.get(Calendar.HOUR) * 60 + currentCal.get(Calendar.MINUTE);
return min2 - min1;
}
答案 1 :(得分:1)
我认为最安全的方法是使用Calendars:
public static boolean sameTime(Date a, Date b) {
Calendar ca = Calendar.getInstance();
ca.setTime(a);
Calendar cb = Calendar.getInstance();
cb.setTime(b);
return ca.get(Calendar.HOUR_OF_DAY) == cb.get(Calendar.HOUR_OF_DAY)
&& ca.get(Calendar.MINUTE) == cb.get(Calendar.MINUTE)
&& ca.get(Calendar.SECOND) == cb.get(Calendar.SECOND)
&& ca.get(Calendar.MILLISECOND) == cb.get(Calendar.MILLISECOND);
}
这将考虑夏令时。
更新:
哦,它没有使用任何弃用的方法。
答案 2 :(得分:0)
另一种方法是使用JODA Time的LocalTime:
public static boolean sameTime(Date a, Date b) {
return new LocalTime(a).compareTo(new LocalTime(b)) == 0;
// equals() or isEquals() may also work depending on your case, you may try
}
答案 3 :(得分:0)
您可以通过使用modulo截断日期来仅比较表示时间的getTime()的毫秒数:
private static long MILLIS_PER_DAY = 1000 * 60 * 60 * 24l;
private static long MILLIS_PER_MINUTE = 1000 * 60l;
public long compareTwoTimeStamps(Timestamp currentTime, Timestamp oldTime)
{
long milliseconds1 = oldTime.getTime() % MILLIS_PER_DAY;
long milliseconds2 = currentTime.getTime() % MILLIS_PER_DAY;
return milliseconds2 - milliseconds1;
// for minutes:
// return (milliseconds2 - milliseconds1) / MILLIS_PER_MINUTE;
}