此问题在此处已有答案:
Add a Double variable representing minute into a Date in Java(3个答案)
Is floating point math broken?(31个答案)
How to add and subtract hours and minutes(4个答案)
Changing Java Date one hour back(11个答案)
昨天关门了。
你好,我试着用Date.getTime()-(时间单位为毫秒)从日期中减去小时,但是结果不正确,与好的结果相比总是有一个微小的差距,有什么想法吗?
if(hoursToBeSubstracted<1) {
float toMinute = hoursToBeSubstracted*60;
return new Date((long)(d1.getTime()-toMinute*60000));
}
return new Date((long)(d1.getTime() - 3600 * hoursToBeSubstracted * 1000));
输出示例:
Before operation Thu Dec 01 13:27:30 CET 2022
Substracting 60.0 minutes
After operation Thu Dec 01 12:28:31 CET 2022
Before operation Wed Nov 30 16:48:52 CET 2022
Substracting 60.0 minutes
After operation Wed Nov 30 15:49:53 CET 2022
Before operation Wed Nov 30 16:48:52 CET 2022
Substracting 60.0 minutes
After operation Wed Nov 30 15:49:53 CET 2022
Before operation Wed Nov 30 16:48:52 CET 2022
Substracting 60.0 minutes
After operation Wed Nov 30 15:49:53 CET 2022
Before operation Thu Dec 01 13:27:30 CET 2022
Substracting 60.0 minutes
After operation Thu Dec 01 12:28:31 CET 2022
1条答案
按热度按时间n8ghc7c11#
java.时间
java.time
API于2014年3月随Java-8一起发布,取代了error-prone legacy date-time API。从那时起,强烈建议使用这种现代的日期-时间API。使用现代日期-时间API的解决方案
将您的
java.util.Date
示例转换为java.time.Instant
,并使用Instant#minus
减去小时数。演示:
输出:
不管出于什么原因,如果您想再次获得
java.util.Date
,可以使用Date#from
来实现。从**Trail: Date Time**了解有关现代日期-时间API的更多信息。