如何在 Java 中对日期执行算术运算?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6537023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I perform arithmetic operation with dates in Java?
提问by AndroidDev
Possible Duplicate:
How to calculate time difference in java?
可能的重复:
如何计算 Java 中的时差?
Actually I want to subtract two dates in Java. I tried a lot but can't succeed. So anyone please help me.
其实我想在Java中减去两个日期。我尝试了很多,但无法成功。所以请任何人帮助我。
Date dtStartDate=pCycMan.getStartDate();
Date dtEndDate=pCycMan.getEndDate();
How can I subtract these two Dates?
我怎样才能减去这两个日期?
采纳答案by Mike Deck
long msDiff = dtEndDate.getTime() - dtStartDate.getTime()
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.
msDiff
现在保存两个日期之间的毫秒数差异。随意使用除法和 mod 运算符转换为其他单位。
回答by aioobe
how can i subtract these two Dates?
我怎样才能减去这两个日期?
You can get the difference in milliseconds like this:
您可以像这样获得以毫秒为单位的差异:
dtEndDate.getTime() - dtStartDate.getTime()
(getTime
returns the number of milliseconds since January 1, 1970, 00:00:00 GMT.)
(getTime
返回自 1970 年 1 月 1 日格林威治标准时间 00:00:00 以来的毫秒数。)
However, for this type of date arithmetics the Joda time library, which has proper classes for time durations (Duration
) is probably a better option.
然而,对于这种类型的日期算术,Joda 时间库,它具有适当的持续时间类 ( Duration
) 可能是更好的选择。
回答by nicholas.hauschild
回答by marchaos
回答by rascio
There is a framework to work with the date in java... http://joda-time.sourceforge.net/userguide.htmltake a look, i'm sure that it can help you
有一个框架可以处理java中的日期...... http://joda-time.sourceforge.net/userguide.html看看,我相信它可以帮助你
回答by RMT
To substract to dates you can get them both as longs getTime()
and subtract the values that are returned.
要减去日期,您可以将它们作为 long 获取getTime()
并减去返回的值。
回答by Bala R
long diffInMillis = dtEndDate.getTimeInMillis() - dtStartDate.getTimeInMillis();
回答by AlexR
It depends what do you want. To get difference in milliseconds say dtStartDate.getTime() - dtEndDate.getTime()
.
这取决于你想要什么。要获得以毫秒为单位的差异,请说dtStartDate.getTime() - dtEndDate.getTime()
。
To get difference in days, hours etc use Calendar class (methods like after, before, compareTo, roll may help).
要获得天数、小时数等的差异,请使用 Calendar 类(诸如 after、before、compareTo、roll 之类的方法可能会有所帮助)。