如何在Java中对日期进行算术运算?
可能的重复:
如何计算java中的时差?
实际上我想减去两个Java 中的日期。我尝试了很多但无法成功。所以请任何人帮助我。
Date dtStartDate=pCycMan.getStartDate();
Date dtEndDate=pCycMan.getEndDate();
如何减去这两个日期?
Possible Duplicate:
How to calculate time difference in java?
Actually I want to subtract two dates in Java. I tried a lot but can't succeed. So anyone please help me.
Date dtStartDate=pCycMan.getStartDate();
Date dtEndDate=pCycMan.getEndDate();
How can I subtract these two Dates?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
msDiff
现在保存两个日期之间的毫秒数差异。请随意使用除法和取模运算符来转换为其他单位。msDiff
now holds the number of milliseconds difference between the two dates. Feel free to use the division and mod operators to convert to other units.您可以像这样得到以毫秒为单位的差异:
(
getTime
返回自 1970 年 1 月 1 日以来的毫秒数, 00:00:00 GMT。)但是,对于这种类型的日期算术,Joda 时间库,它具有适当的持续时间类(
Duration
)可能是更好的选择。You can get the difference in milliseconds like this:
(
getTime
returns the number of milliseconds since January 1, 1970, 00:00:00 GMT.)However, for this type of date arithmetics the Joda time library, which has proper classes for time durations (
Duration
) is probably a better option.要减去日期,您可以将它们作为 longs
getTime()
获取,然后减去返回的值。To substract to dates you can get them both as longs
getTime()
and subtract the values that are returned.根据这些日期创建两个 Calendar 对象然后使用 add() 方法(也可用于对日期进行细分)。
Create two Calendar objects from those Dates and then use the add() method (which can be used to subtrade dates too).
有一个在java中处理日期的框架......
http://joda-time.sourceforge.net/userguide.html
看一下,我相信它可以帮助你
There is a framework to work with the date in java...
http://joda-time.sourceforge.net/userguide.html
take a look, i'm sure that it can help you
这取决于你想要什么。要获得以毫秒为单位的差异,请说
dtStartDate.getTime() - dtEndDate.getTime()
。要获得天、小时等的差异,请使用 Calendar 类(after、before、compareTo、roll 等方法可能会有所帮助)。
It depends what do you want. To get difference in milliseconds say
dtStartDate.getTime() - dtEndDate.getTime()
.To get difference in days, hours etc use Calendar class (methods like after, before, compareTo, roll may help).
使用 Calendar 类。
用法:
Use the Calendar class.
Usage: