gpt4 book ai didi

java - 如何只比较 java.sql.TimeStamp 的时间

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:44:13 24 4
gpt4 key购买 nike

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;
}

上面的代码也考虑了日期。我需要比较 Timestamp 的 2 个实例,并且只比较 Timestamp 的时间部分。不应考虑日期。每当我比较它时,比较也会考虑日期。

最佳答案

一种解决方案,使用 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();
currentCal.setTime(currentTime);
long min2 = currentCal.get(Calendar.HOUR) * 60 + currentCal.get(Calendar.MINUTE);
return min2 - min1;
}

关于java - 如何只比较 java.sql.TimeStamp 的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29619880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com