计算两个 Java 日期实例之间的差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1555262/
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
Calculating the difference between two Java date instances
提问by pr1001
I'm using Java's java.util.Date
class in Scala and want to compare a Date
object and the current time. I know I can calculate the delta by using getTime():
我java.util.Date
在 Scala 中使用 Java 的类,想比较一个Date
对象和当前时间。我知道我可以使用 getTime() 计算增量:
(new java.util.Date()).getTime() - oldDate.getTime()
However, this just leaves me with a long
representing milliseconds. Is there any simpler, nicer way to get a time delta?
然而,这只是给我留下了一个long
代表毫秒。有没有更简单、更好的方法来获得时间增量?
采纳答案by notnoop
The JDK Date
API is horribly broken unfortunately. I recommend using Joda Time library.
Date
不幸的是,JDK API 严重损坏。我建议使用Joda Time 库。
Joda Time has a concept of time Interval:
Joda Time 有一个时间间隔的概念:
Interval interval = new Interval(oldTime, new Instant());
EDIT: By the way, Joda has two concepts: Interval
for representing an interval of time between two time instants (represent time between 8am and 10am), and a Duration
that represents a length of time without the actual time boundaries (e.g. represent two hours!)
编辑:顺便说一下,Joda 有两个概念:Interval
用于表示两个时间瞬间之间的时间间隔(表示上午 8 点到 10 点之间的时间),以及Duration
表示没有实际时间边界的时间长度(例如表示两个小时!)
If you only care about time comparisions, most Date
implementations (including the JDK one) implements Comparable
interface which allows you to use the Comparable.compareTo()
如果您只关心时间比较,大多数Date
实现(包括 JDK 的实现)都实现了Comparable
允许您使用Comparable.compareTo()
回答by gustafc
回答by Rob H
回答by Andrzej Doyle
That's probably the most straightforward way to do it - perhaps it's because I've been coding in Java (with its admittedly clunky date and time libraries) for a while now, but that code looks "simple and nice" to me!
这可能是最直接的方法 - 可能是因为我已经用 Java 编码(其公认的笨重的日期和时间库)已经有一段时间了,但该代码对我来说看起来“简单而漂亮”!
Are you happy with the result being returned in milliseconds, or is part of your question that you would prefer to have it returned in some alternative format?
您是否对以毫秒为单位返回的结果感到满意,或者您的问题的一部分是您希望以某种替代格式返回结果?
回答by Michael Borgwardt
A slightly simpler alternative:
一个稍微简单的替代方案:
System.currentTimeMillis() - oldDate.getTime()
As for "nicer": well, what exactly do you need? The problem with representing time durations as a number of hours and days etc. is that it may lead to inaccuracies and wrong expectations due to the complexity of dates (e.g. days can have 23 or 25 hours due to daylight savings time).
至于“更好”:嗯,你到底需要什么?将持续时间表示为小时和天数等的问题在于,由于日期的复杂性(例如,由于夏令时,天可能有 23 或 25 小时),这可能会导致不准确和错误的预期。
回答by Jon Skeet
You need to define your problem more clearly. You couldjust take the number of milliseconds between the two Date
objects and divide by the number of milliseconds in 24 hours, for example... but:
你需要更清楚地定义你的问题。例如,您可以将两个Date
对象之间的毫秒数除以 24 小时内的毫秒数……但是:
- This won't take time zones into consideration -
Date
is always in UTC - This won't take daylight saving time into consideration (where there can be days which are only 23 hours long, for example)
- Even within UTC, how many days are there in August 16th 11pm to August 18th 2am? It's only 27 hours, so does that mean one day? Or should it be three days because it covers three dates?
- 这不会考虑时区 -
Date
总是在 UTC - 这不会考虑夏令时(例如,可能有几天只有 23 小时)
- 即使在 UTC 范围内,8 月 16 日晚上 11 点到 8 月 18 日凌晨 2 点有多少天?只有27小时,所以这意味着一天吗?还是应该是三天,因为它涵盖了三个日期?
回答by PaulJWilliams
Just call getTime on each, take the difference, and divide by the number of milliseconds in a day.
只需在每个上调用 getTime,取差值,然后除以一天中的毫秒数。
回答by Bozho
int daysDiff = (date1.getTime() - date2.getTime()) / MILLIS_PER_DAY;
回答by codersarepeople
If you have d1 and d2 as your dates, the best solution is probably the following:
如果您将 d1 和 d2 作为日期,则最佳解决方案可能如下:
int days1 = d1.getTime()/(60*60*24*1000);//find the number of days since the epoch.
int days2 = d2.getTime()/(60*60*24*1000);
then just say
那么就说
days2-days1
or whatever
管他呢
回答by YoK
Check example here http://www.roseindia.net/java/beginners/DateDifferent.shtmlThis example give you difference in days, hours, minutes, secs and milli sec's :).
在此处查看示例http://www.roseindia.net/java/beginners/DateDifferent.shtml这个示例为您提供了天数、小时数、分钟数、秒数和毫秒数的差异:)。
import java.util.Calendar;
import java.util.Date;
public class DateDifferent {
public static void main(String[] args) {
Date date1 = new Date(2009, 01, 10);
Date date2 = new Date(2009, 07, 01);
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.setTime(date1);
calendar2.setTime(date2);
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("\nThe Date Different Example");
System.out.println("Time in milliseconds: " + diff + " milliseconds.");
System.out.println("Time in seconds: " + diffSeconds + " seconds.");
System.out.println("Time in minutes: " + diffMinutes + " minutes.");
System.out.println("Time in hours: " + diffHours + " hours.");
System.out.println("Time in days: " + diffDays + " days.");
}
}