Java 库,将两个 Date 对象相加/相减,精度达到毫秒
我正在查看 java Date 库 1. java.util.Date, 2. 日期4J 3. Joda-time
看看我是否可以对两个日期对象执行时间减法,精确到毫秒。
我收到 2011-05-29T22:50:12.692 作为字符串,并通过使用 SimpleDateFormat 解析它将其转换为 Date 对象。
另一个 Date 对象也将收到一个 String。我想从两个 Date 对象中减去。
有什么想法吗?
基本上我想获得两个 Date 对象之间的间隔,精确到毫秒。
I was looking thru java Date libraries
1. java.util.Date,
2. Date4J
3. Joda-time
to find out whether I can perform time subtraction to two Date Objects, to the precision of milliseconds.
I receive 2011-05-29T22:50:12.692 as a String, and convert it into a Date object by parsing it with SimpleDateFormat.
The other Date object will also be received a String. and I want to subtract from two Date objects.
Any ideas?
Basically i want to get an interval between the two Date objects, to the precision of milliseconds.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
尝试使用 Date.getTime()
编辑
这假设
d2
按时间顺序晚于d1
。Try using Date.getTime()
EDIT
This assumes that
d2
is chronologically afterd1
.在 java.util.Date 中有一个名为
Date.getTime()
的方法,您可以使用它来获取以英里为单位的时间。in java.util.Date there is a method called
Date.getTime()
that you can use to get the time in milies.你的意思是这样吗?
Do you mean like this?
Date() 对象的内部表示是纪元过去的毫秒数。只需使用 getTime() 方法获取这些值并对它们进行算术即可。然后,您可以根据该值构造一个新的 Date 对象,然后就完成了。
The internal representation of a Date() object is the number of milliseconds past the epoch. Just get those values with the getTime() method and do arithmetic on them. You can then construct a new Date object based on that value and you are done.
只需获取毫秒差异:
Just get the millisecond difference:
您可以利用 XMLGregorianCalendar 而不是 SimpleDateFormat (注意 SimpleDateFormat 不是线程安全的: http://www.codefutures.com/weblog/andygrove/2007/10/simpledateformat-and-thread-safety.html):
You could leverage XMLGregorianCalendar instead of SimpleDateFormat (Note SimpleDateFormat is not thread safe: http://www.codefutures.com/weblog/andygrove/2007/10/simpledateformat-and-thread-safety.html):
这就是您想要的:
解释:
返回日期之间的毫秒差
创建一个新的 Date 对象,设置为自纪元以来的毫秒数。
编辑
如果您只想要正差异,请将其更改为此。这样,输入的顺序并不重要:
This is what you want:
Explanation:
Returns millisecond difference between the dates
Creates a new Date object set to number of milliseconds since epoch.
Edit
IF you only want the positive difference, change it to this. This way it doesn't matter what order you put in inputs: