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的java.util。Scala中的Date类,并希望比较日期对象和当前时间。我知道我可以用getTime()来计算delta:
(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?
然而,这只给我留下了一个长表示毫秒的时间。有没有更简单,更好的方法来得到时间增量?
43 个解决方案
#1
169
The JDK Date
API is horribly broken unfortunately. I recommend using Joda Time library.
JDK Date API不幸被严重破坏。我推荐使用Joda时间库。
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有两个概念:间隔时间表示两个时间间隔之间的时间间隔(表示8点到10点之间的时间),以及一个表示时间长度的持续时间,没有实际的时间边界(例如,代表两个小时!)
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()
如果您只关心时间比较,那么大多数日期实现(包括JDK)实现了可比接口,允许您使用Comparable.compareTo()
#2
457
Simple diff (without lib)
/**
* Get a diff between two dates
* @param date1 the oldest date
* @param date2 the newest date
* @param timeUnit the unit in which you want the diff
* @return the diff value, in the provided unit
*/
public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
long diffInMillies = date2.getTime() - date1.getTime();
return timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
}
And then can you call:
然后你可以打电话:
getDateDiff(date1,date2,TimeUnit.MINUTES);
to get the diff of the 2 dates in minutes unit.
在分钟单元中得到2个日期的差值。
TimeUnit
is java.util.concurrent.TimeUnit
, a standard Java enum going from nanos to days.
TimeUnit是java . util . concurrent。TimeUnit,从nanos到days的标准Java enum。
Human readable diff (without lib)
public static Map<TimeUnit,Long> computeDiff(Date date1, Date date2) {
long diffInMillies = date2.getTime() - date1.getTime();
List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));
Collections.reverse(units);
Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>();
long milliesRest = diffInMillies;
for ( TimeUnit unit : units ) {
long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
long diffInMilliesForUnit = unit.toMillis(diff);
milliesRest = milliesRest - diffInMilliesForUnit;
result.put(unit,diff);
}
return result;
}
http://ideone.com/5dXeu6
The output is something like Map:{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0}
, with the units ordered.
输出如下图所示:{天=1,小时=3,分钟=46,秒=40,毫秒=0,微秒=0,纳秒=0},单位有序。
You just have to convert that map to an user-friendly string.
您只需将该映射转换为用户友好的字符串。
Warning
The above code snippets compute a simple diff between 2 instants. It can cause problems during a daylight saving switch, like explained in this post. This means if you compute the diff between dates with no time you may have a missing day/hour.
上面的代码片段计算两个瞬间之间的简单差异。它会在日光节约开关期间引起问题,如本文所述。这意味着如果你在没有时间的情况下计算日期之间的差异,你可能会错过一天或一小时。
In my opinion the date diff is kind of subjective, especially on days. You may:
在我看来,日期差异是有点主观的,尤其是在白天。你可以:
-
count the number of 24h elapsed time: day+1 - day = 1 day = 24h
计算24小时运行时间:日+1 -日= 1天= 24小时。
-
count the number of elapsed time, taking care of daylight savings: day+1 - day = 1 = 24h (but using midnight time and daylight savings it could be 0 day and 23h)
计算运行时间的数量,注意日光节约:天+1 -天= 1 = 24小时(但使用午夜时间和夏令时,可能是0天和23小时)
-
count the number of
day switches
, which means day+1 1pm - day 11am = 1 day, even if the elapsed time is just 2h (or 1h if there is a daylight saving :p)计算一天开关的数量,这意味着一天+1个下午-第11am = 1天,即使经过的时间仅为2h(如果有夏令时,则为1h:p)
My answer is valid if your definition of date diff on days match the 1st case
我的回答是有效的,如果你对日期的定义与第一个情况相符
With JodaTime
If you are using JodaTime you can get the diff for 2 instants (millies backed ReadableInstant) dates with:
如果你正在使用JodaTime,你可以用以下两种方式获得diff:
Interval interval = new Interval(oldInstant, new Instant());
But you can also get the diff for Local dates/times:
但你也可以得到当地日期/时间的差异:
// returns 4 because of the leap year of 366 days
new Period(LocalDate.now(), LocalDate.now().plusDays(365*5), PeriodType.years()).getYears()
// this time it returns 5
new Period(LocalDate.now(), LocalDate.now().plusDays(365*5+1), PeriodType.years()).getYears()
// And you can also use these static methods
Years.yearsBetween(LocalDate.now(), LocalDate.now().plusDays(365*5)).getYears()
#3
142
int diffInDays = (int)( (newerDate.getTime() - olderDate.getTime())
/ (1000 * 60 * 60 * 24) )
Note that this works with UTC dates, so the difference may be a day off if you look at local dates. And getting it to work correctly with local dates requires a completely different approach due to daylight savings time.
注意,这适用于UTC日期,因此如果查看本地日期,差异可能是休息日。由于夏令时,要让它在本地日期上正常工作需要一种完全不同的方法。
#4
52
You need to define your problem more clearly. You could just take the number of milliseconds between the two Date
objects and divide by the number of milliseconds in 24 hours, for example... but:
你需要更清楚地定义你的问题。您可以取两个日期对象之间的毫秒数,然后除以24小时内的毫秒数,例如……但是:
- This won't take time zones into consideration -
Date
is always in UTC - 这不会考虑时区——日期总是在UTC
- This won't take daylight saving time into consideration (where there can be days which are only 23 hours long, for example)
- 这就不需要考虑夏令时(例如,有些天可能只有23小时)
- 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?
- 即使在UTC, 8月16日晚上11点到8月18日凌晨2点有多少天?只有27个小时,那意味着有一天吗?或者应该是三天,因为它包含三个日期?
#5
37
Using the java.time framework built into Java 8+:
使用java。Java 8+内置的时间框架:
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime oldDate = now.minusDays(1).minusMinutes(10);
Duration duration = Duration.between(oldDate, now);
System.out.println("ISO-8601: " + duration);
System.out.println("Minutes: " + duration.toMinutes());
Output:
输出:
ISO-8601: PT24H10M
iso - 8601:PT24H10M
Minutes: 1450
分钟:1450
For more info, see the Oracle Tutorial and the ISO 8601 standard.
有关更多信息,请参阅Oracle教程和ISO 8601标准。
#6
34
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
http://joda-time.sourceforge.net/faq.html#datediff
http://joda-time.sourceforge.net/faq.html datediff
#7
30
tl;dr
Convert your obsolete java.util.Date
objects to their replacement, java.time.Instant
. Then calculate the elapsed time as a Duration
.
把过时的java.util。为对象的替换对象(java.time.Instant)设定日期。然后计算运行时间作为持续时间。
Duration d =
Duration.between( // Calculate the span of time between two moments as a number of hours, minutes, and seconds.
myJavaUtilDate.toInstant() , // Convert legacy class to modern class by calling new method added to the old class.
Instant.now() // Capture the current moment in UTC. About two and a half hours later in this example.
)
;
d.toString(): PT2H34M56S
d.toString():PT2H34M56S
d.toMinutes(): 154
d.toMinutes():154
d.toMinutesPart(): 34
d.toMinutesPart():34
ISO 8601 Format: PnYnMnDTnHnMnS
The sensible standard ISO 8601 defines a concise textual representation of a span of time as a number of years, months, days, hours, etc. The standard calls such such a span a duration. The format is PnYnMnDTnHnMnS
where the P
means "Period", the T
separates the date portion from the time portion, and in between are numbers followed by a letter.
合理的标准ISO 8601定义了时间跨度的简明文本表示形式,如年、月、日、小时等。该格式是PnYnMnDTnHnMnS,其中P为“Period”,T将日期部分与时间部分分开,中间是数字,后面是字母。
Examples:
例子:
-
P3Y6M4DT12H30M5S
three years, six months, four days, twelve hours, thirty minutes, and five seconds - 3年,6个月,4天,12小时,30分钟,5秒。
-
PT4H30M
Four and a half hours - PT4H30M 4.5小时
java.time
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date
/java.util.Calendar
classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
java。在Java 8中构建的时间框架,随后取代了麻烦的*ava .util. date / Java .util。日历类。新类的灵感来自于非常成功的Joda-Time框架,它的目标是作为它的继承者,在概念上类似,但是重新架构。由JSR 310定义的。延长了三个额外的项目。看教程。
Moment
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
即时类表示在UTC时间轴上的一个时刻,其分辨率为纳秒(最高为9(9)位小数)。
Instant instant = Instant.now() ; // Capture current moment in UTC.
Best to avoid the legacy classes such as Date
/Calendar
. But if you must inter-operate with old code not yet updated to java.time, convert back and forth. Call new conversion methods added to the old classes. For moving from a java.util.Date
to an Instant
, call Date::toInstant
.
最好避免遗留类,如日期/日历。但是,如果您必须与尚未更新到java的旧代码进行互操作的话。时间,来回转换。调用添加到旧类的新转换方法。从java.util移动。立即约会,打电话日期::立即。
Instant instant = myJavaUtilDate.toInstant() ; // Convert from legacy `java.util.Date` class to modern `java.time.Instant` class.
Span of time
The java.time classes have split this idea of representing a span of time as a number of years, months, days, hours, minutes, seconds into two halves:
java。时间课程将时间跨度分成两部分:年份、月、天、小时、分钟、秒。
Here is an example.
这是一个例子。
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now ( zoneId );
ZonedDateTime future = now.plusMinutes ( 63 );
Duration duration = Duration.between ( now , future );
Dump to console.
转储到控制台。
Both Period
and Duration
use the ISO 8601 standard for generating a String representation of their value.
期间和持续时间都使用ISO 8601标准来生成它们的值的字符串表示形式。
System.out.println ( "now: " + now + " to future: " + now + " = " + duration );
now: 2015-11-26T00:46:48.016-05:00[America/Montreal] to future: 2015-11-26T00:46:48.016-05:00[America/Montreal] = PT1H3M
现在:2015-11-26 t00:46 . 08 -05:00[美国/蒙特利尔]to future: 2015-11-26 t00:46 . 08 -05:00[美国/蒙特利尔]= PT1H3M
Java 9 adds methods to Duration
to get the days part, hours part, minutes part, and seconds part.
Java 9向持续时间添加方法,以获得天数部分、小时部分、分钟部分和秒部分。
You can get the total number of days or hours or minutes or seconds or milliseconds or nanoseconds in the entire Duration.
您可以在整个持续时间内获得天数、小时、分钟、秒、毫秒或纳秒的总数。
long totalHours = duration.toHours();
In Java 9 the Duration
class gets new methods for returning the various parts of days, hours, minutes, seconds, milliseconds/nanoseconds. Call the to…Part
methods: toDaysPart()
, toHoursPart()
, and so on.
在Java 9中,持续时间类获得了新的方法,用于返回日、小时、分钟、秒、毫秒/纳秒的不同部分。调用to…Part方法:toDaysPart(), toHoursPart(),等等。
ChronoUnit
If you only care about a simpler larger granularity of time, such as “number of days elapsed”, use the ChronoUnit
enum.
如果您只关心更简单的更大粒度的时间,例如“已经过的天数”,则使用ChronoUnit enum。
long daysElapsed = ChronoUnit.DAYS.between( earlier , later );
Another example.
另一个例子。
Instant now = Instant.now();
Instant later = now.plus( Duration.ofHours( 2 ) );
…
long minutesElapsed = ChronoUnit.MINUTES.between( now , later );
120
120年
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
java。time框架被构建到Java 8以及以后的版本中。这些类取代了麻烦的旧遗留日期时间类(如java.util)。日期,日历,& SimpleDateFormat。
The Joda-Time project, now in maintenance mode, advises migration to java.time.
现在处于维护模式的Joda-Time项目建议迁移到java.time。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle教程。和搜索堆栈溢出为许多例子和解释。规范是JSR 310。
Where to obtain the java.time classes?
在哪里获得java。时间类?
-
Java SE 8 and SE 9 and later
- Built-in.
- 内置的。
- Part of the standard Java API with a bundled implementation.
- 带有捆绑实现的标准Java API的一部分。
- Java 9 adds some minor features and fixes.
- Java 9添加了一些次要的特性和修复。
- Java SE 8和SE 9,以及后来的内置。带有捆绑实现的标准Java API的一部分。Java 9添加了一些次要的特性和修复。
-
Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- 大部分java。时间功能在三个回端移植到Java 6和7。
- Java SE 6和SE 7大部分的Java。时间功能在三个回端移植到Java 6和7。
-
Android
- The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
- ThreeTenABP项目特别适用于Android。
- See How to use….
- 看到如何使用....
- Android的ThreeTenABP项目特别适用于Android的ThreeTen-Backport(上面提到的)。看到如何使用....
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
三个额外的项目扩展了java。时间和额外的类。这个项目是java.time未来可能增加的一个试验场。您可以在这里找到一些有用的课程,如间隔、年周、年季等。
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. I leave this section intact for history.
更新:Joda-Time项目现在处于维护模式,团队建议迁移到java。时间类。我把这一节完整地留给历史。
The Joda-Time library uses ISO 8601 for its defaults. Its Period
class parses and generates these PnYnMnDTnHnMnS strings.
Joda-Time库默认使用ISO 8601。它的周期类解析并生成这些pnynmndhnmns字符串。
DateTime now = DateTime.now(); // Caveat: Ignoring the important issue of time zones.
Period period = new Period( now, now.plusHours( 4 ).plusMinutes( 30));
System.out.println( "period: " + period );
Renders:
呈现:
period: PT4H30M
#8
22
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小时)。
#9
20
Using millisecond approach can cause problems in some locales.
使用毫秒级的方法可能会在某些地区引起问题。
Lets take, for example, the difference between the two dates 03/24/2007 and 03/25/2007 should be 1 day;
以2007年3月24日和2007年3月25日这两个日期的差值为1天为例;
However, using the millisecond route, you'll get 0 days, if you run this in the UK!
然而,如果你在英国运行这个程序,使用毫秒级的路由,你将得到0天!
/** Manual Method - YIELDS INCORRECT RESULTS - DO NOT USE**/
/* This method is used to find the no of days between the given dates */
public long calculateDays(Date dateEarly, Date dateLater) {
return (dateLater.getTime() - dateEarly.getTime()) / (24 * 60 * 60 * 1000);
}
Better way to implement this is to use java.util.Calendar
更好的实现方法是使用java.util.Calendar
/** Using Calendar - THE CORRECT WAY**/
public static long daysBetween(Calendar startDate, Calendar endDate) {
Calendar date = (Calendar) startDate.clone();
long daysBetween = 0;
while (date.before(endDate)) {
date.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}
#10
19
There are many ways you can find the difference between dates & times. One of the simplest ways that I know of would be:
你可以用很多方法找到日期和时间的不同之处。我所知道的最简单的方法之一是:
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.set(2012, 04, 02);
calendar2.set(2012, 04, 04);
long milsecs1= calendar1.getTimeInMillis();
long milsecs2 = calendar2.getTimeInMillis();
long diff = milsecs2 - milsecs1;
long dsecs = diff / 1000;
long dminutes = diff / (60 * 1000);
long dhours = diff / (60 * 60 * 1000);
long ddays = diff / (24 * 60 * 60 * 1000);
System.out.println("Your Day Difference="+ddays);
The print statement is just an example - you can format it, the way you like.
print语句只是一个示例——您可以按自己喜欢的方式格式化它。
#11
12
Since all the answers here are correct but use legacy java or 3rd party libs like joda or similar, I will just drop another way using new java.time classes in Java 8 and later. See Oracle Tutorial.
由于这里所有的答案都是正确的,但是使用遗留java或第三方libs,如joda或类似的,我将使用新的java放弃另一种方式。Java 8及以后的时间类。看到甲骨文教程。
Use LocalDate
and ChronoUnit
:
使用LocalDate ChronoUnit:
LocalDate d1 = LocalDate.of(2017, 5, 1);
LocalDate d2 = LocalDate.of(2017, 5, 18);
long days = ChronoUnit.DAYS.between(d1, d2);
System.out.println( days );
#12
9
Subtracting the dates in milliseconds works (as described in another post), but you have to use HOUR_OF_DAY and not HOUR when clearing the time parts of your dates:
以毫秒为单位减去日期是有效的(如另一篇文章所描述的),但是你必须使用一小时或一天,而不是一小时来清理你的日期部分:
public static final long MSPERDAY = 60 * 60 * 24 * 1000;
...
final Calendar dateStartCal = Calendar.getInstance();
dateStartCal.setTime(dateStart);
dateStartCal.set(Calendar.HOUR_OF_DAY, 0); // Crucial.
dateStartCal.set(Calendar.MINUTE, 0);
dateStartCal.set(Calendar.SECOND, 0);
dateStartCal.set(Calendar.MILLISECOND, 0);
final Calendar dateEndCal = Calendar.getInstance();
dateEndCal.setTime(dateEnd);
dateEndCal.set(Calendar.HOUR_OF_DAY, 0); // Crucial.
dateEndCal.set(Calendar.MINUTE, 0);
dateEndCal.set(Calendar.SECOND, 0);
dateEndCal.set(Calendar.MILLISECOND, 0);
final long dateDifferenceInDays = ( dateStartCal.getTimeInMillis()
- dateEndCal.getTimeInMillis()
) / MSPERDAY;
if (dateDifferenceInDays > 15) {
// Do something if difference > 15 days
}
#13
8
Take a look at Joda Time, which is an improved Date/Time API for Java and should work fine with Scala.
让我们来看看Joda Time,它是一个改进的Java日期/时间API,应该可以很好地使用Scala。
#14
8
If you don't want to use JodaTime or similar, the best solution is probably this:
如果你不想使用JodaTime或类似的方法,最好的解决方案可能是:
final static long MILLIS_PER_DAY = 24 * 3600 * 1000;
long msDiff= date1.getTime() - date2.getTime();
long daysDiff = Math.round(msDiff / ((double)MILLIS_PER_DAY));
The number of ms per day is not always the same (because of daylight saving time and leap seconds), but it's very close, and at least deviations due to daylight saving time cancel out over longer periods. Therefore dividing and then rounding will give a correct result (at least as long as the local calendar used does not contain weird time jumps other than DST and leap seconds).
每天的毫秒数并不总是相同的(因为夏令时和闰秒),但是非常接近,而且至少由于夏令时的偏差会在更长时间内抵消掉。因此,分割然后舍入将得到正确的结果(至少只要所使用的本地日历不包含除DST和闰秒之外的奇怪时间跳转)。
Note that this still assumes that date1
and date2
are set to the same time of day. For different times of day, you'd first have to define what "date difference" means, as pointed out by Jon Skeet.
注意,这仍然假设date1和date2被设置为一天中的相同时间。对于一天中不同的时间,你首先要定义“日期差异”是什么意思,正如Jon Skeet指出的。
#15
5
Let me show difference between Joda Interval and Days:
让我来展示一下Joda Interval和Days之间的差异:
DateTime start = new DateTime(2012, 2, 6, 10, 44, 51, 0);
DateTime end = new DateTime(2012, 2, 6, 11, 39, 47, 1);
Interval interval = new Interval(start, end);
Period period = interval.toPeriod();
System.out.println(period.getYears() + " years, " + period.getMonths() + " months, " + period.getWeeks() + " weeks, " + period.getDays() + " days");
System.out.println(period.getHours() + " hours, " + period.getMinutes() + " minutes, " + period.getSeconds() + " seconds ");
//Result is:
//0 years, 0 months, *1 weeks, 1 days*
//0 hours, 54 minutes, 56 seconds
//Period can set PeriodType,such as PeriodType.yearMonthDay(),PeriodType.yearDayTime()...
Period p = new Period(start, end, PeriodType.yearMonthDayTime());
System.out.println(p.getYears() + " years, " + p.getMonths() + " months, " + p.getWeeks() + " weeks, " + p.getDays() + "days");
System.out.println(p.getHours() + " hours, " + p.getMinutes() + " minutes, " + p.getSeconds() + " seconds ");
//Result is:
//0 years, 0 months, *0 weeks, 8 days*
//0 hours, 54 minutes, 56 seconds
#16
5
If you need a formatted return String like "2 Days 03h 42m 07s", try this:
如果您需要一个格式化的返回字符串,如“2天03h 42m 07s”,请尝试以下操作:
public String fill2(int value)
{
String ret = String.valueOf(value);
if (ret.length() < 2)
ret = "0" + ret;
return ret;
}
public String get_duration(Date date1, Date date2)
{
TimeUnit timeUnit = TimeUnit.SECONDS;
long diffInMilli = date2.getTime() - date1.getTime();
long s = timeUnit.convert(diffInMilli, TimeUnit.MILLISECONDS);
long days = s / (24 * 60 * 60);
long rest = s - (days * 24 * 60 * 60);
long hrs = rest / (60 * 60);
long rest1 = rest - (hrs * 60 * 60);
long min = rest1 / 60;
long sec = s % 60;
String dates = "";
if (days > 0) dates = days + " Days ";
dates += fill2((int) hrs) + "h ";
dates += fill2((int) min) + "m ";
dates += fill2((int) sec) + "s ";
return dates;
}
#17
4
Check example here http://www.roseindia.net/java/beginners/DateDifferent.shtml This example give you difference in days, hours, minutes, secs and milli sec's :).
这里检查示例http://www.roseindia.net/java/beginners/datedifference .shtml此示例以天、小时、分钟、secs和milli sec:为单位给出不同的示例。
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.");
}
}
#18
4
Use GMT time zone to get an instance of the Calendar, set the time using the set method of Calendar class. The GMT timezone has 0 offset (not really important) and daylight saving time flag set to false.
使用GMT时区获取日历实例,使用Calendar类的set方法设置时间。GMT时区的偏移量为0(并不重要),夏令时标志设置为false。
final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.set(Calendar.YEAR, 2011);
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.DAY_OF_MONTH, 29);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
final Date startDate = cal.getTime();
cal.set(Calendar.YEAR, 2011);
cal.set(Calendar.MONTH, 12);
cal.set(Calendar.DAY_OF_MONTH, 21);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
final Date endDate = cal.getTime();
System.out.println((endDate.getTime() - startDate.getTime()) % (1000l * 60l * 60l * 24l));
#19
4
Following code can give you the desired output:
下面的代码可以给你想要的输出:
String startDate = "Jan 01 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd yyyy");
LocalDate date = LocalDate.parse(startDate, formatter);
String currentDate = "Feb 11 2015";
LocalDate date1 = LocalDate.parse(currentDate, formatter);
System.out.println(date1.toEpochDay() - date.toEpochDay());
#20
4
public static String getDifferenceBtwTime(Date dateTime) {
long timeDifferenceMilliseconds = new Date().getTime() - dateTime.getTime();
long diffSeconds = timeDifferenceMilliseconds / 1000;
long diffMinutes = timeDifferenceMilliseconds / (60 * 1000);
long diffHours = timeDifferenceMilliseconds / (60 * 60 * 1000);
long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
long diffWeeks = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 7);
long diffMonths = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 30.41666666));
long diffYears = (long)(timeDifferenceMilliseconds / (1000 * 60 * 60 * 24 * 365));
if (diffSeconds < 1) {
return "one sec ago";
} else if (diffMinutes < 1) {
return diffSeconds + " seconds ago";
} else if (diffHours < 1) {
return diffMinutes + " minutes ago";
} else if (diffDays < 1) {
return diffHours + " hours ago";
} else if (diffWeeks < 1) {
return diffDays + " days ago";
} else if (diffMonths < 1) {
return diffWeeks + " weeks ago";
} else if (diffYears < 12) {
return diffMonths + " months ago";
} else {
return diffYears + " years ago";
}
}
#21
3
int daysDiff = (date1.getTime() - date2.getTime()) / MILLIS_PER_DAY;
#22
3
Best thing to do is
最好的办法是
(Date1-Date2)/86 400 000
That number is the number of milliseconds in a day.
这个数字是一天的毫秒数。
One date-other date gives you difference in milliseconds.
一个日期-另一个日期以毫秒为单位。
Collect the answer in a double variable.
在双变量中收集答案。
#23
2
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?
您是否满意于以毫秒为单位返回的结果,还是您希望以其他格式返回的问题的一部分?
#24
2
Not using the standard API, no. You can roll your own doing something like this:
不使用标准API。你可以自己做这样的事情:
class Duration {
private final TimeUnit unit;
private final long length;
// ...
}
Or you can use Joda:
或者你可以用Joda:
DateTime a = ..., b = ...;
Duration d = new Duration(a, b);
#25
2
Note: startDate and endDates are -> java.util.Date
注意:startDate和endDates是-> java.util.Date
import org.joda.time.Duration;
import org.joda.time.Interval;
Interval interval = new Interval(startDate.getTime(), endDate.getTime);
Duration period = interval.toDuration();
period.getStandardDays() //gives the number of days elapsed between start and end date
Similar to days, you can also get hours, minutes and seconds
与白天类似,你也可以得到小时、分钟和秒
period.getStandardHours();
period.getStandardMinutes();
period.getStandardSeconds();
#26
2
Just to answer the initial question:
为了回答最初的问题:
Put the following code in a Function like Long getAge(){}
将以下代码放在一个函数中,如Long getAge(){}
Date dahora = new Date();
long MillisToYearsByDiv = 1000l *60l * 60l * 24l * 365l;
long javaOffsetInMillis = 1990l * MillisToYearsByDiv;
long realNowInMillis = dahora.getTime() + javaOffsetInMillis;
long realBirthDayInMillis = this.getFechaNac().getTime() + javaOffsetInMillis;
long ageInMillis = realNowInMillis - realBirthDayInMillis;
return ageInMillis / MillisToYearsByDiv;
The most important here is to work with long numbers when multiplying and dividing. And of course, the offset that Java applies in its calculus of Dates.
这里最重要的是在乘法和除法时使用长数字。当然,Java在其日期演算中应用的偏移量。
:)
:)
#27
1
try this:
试试这个:
int epoch = (int) (new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 00:00:00").getTime() / 1000);
you can edit the string in the parse() methods param.
可以在parse()方法的param中编辑字符串。
#28
1
Since you are using Scala, there is a very good Scala library Lamma. With Lamma you can minus date directly with -
operator
因为您正在使用Scala,所以有一个非常好的Scala库Lamma。有了Lamma,你可以直接用-算符减去日期
scala> Date(2015, 5, 5) - 2 // minus days by int
res1: io.lamma.Date = Date(2015,5,3)
scala> Date(2015, 5, 15) - Date(2015, 5, 8) // minus two days => difference between two days
res2: Int = 7
#29
1
Just use below method with two Date
objects. If you want to pass current date, just pass new Date()
as a second parameter as it is initialised with current time.
使用下面的方法来处理两个日期对象。如果希望传递当前日期,只需将new date()作为第二个参数传递,因为它是用当前时间初始化的。
public String getDateDiffString(Date dateOne, Date dateTwo)
{
long timeOne = dateOne.getTime();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return "dateTwo is " + delta + " days after dateOne";
}
else {
delta *= -1;
return "dateTwo is " + delta + " days before dateOne";
}
}
Also, apart from from number of days, if, you want other parameter difference too, use below snippet,
另外,除了天数之外,如果您还想要其他参数的差异,请使用下面的代码片段,
int year = delta / 365;
int rest = delta % 365;
int month = rest / 30;
rest = rest % 30;
int weeks = rest / 7;
int days = rest % 7;
P.S Code is entirely taken from an SO answer.
P。S的代码完全取自一个SO答案。
#30
1
Earlier versions of Java you can try.
您可以尝试早期版本的Java。
public static String daysBetween(Date createdDate, Date expiryDate) {
Calendar createdDateCal = Calendar.getInstance();
createdDateCal.clear();
createdDateCal.setTime(createdDate);
Calendar expiryDateCal = Calendar.getInstance();
expiryDateCal.clear();
expiryDateCal.setTime(expiryDate);
long daysBetween = 0;
while (createdDateCal.before(expiryDateCal)) {
createdDateCal.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween+"";
}
#1
169
The JDK Date
API is horribly broken unfortunately. I recommend using Joda Time library.
JDK Date API不幸被严重破坏。我推荐使用Joda时间库。
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有两个概念:间隔时间表示两个时间间隔之间的时间间隔(表示8点到10点之间的时间),以及一个表示时间长度的持续时间,没有实际的时间边界(例如,代表两个小时!)
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()
如果您只关心时间比较,那么大多数日期实现(包括JDK)实现了可比接口,允许您使用Comparable.compareTo()
#2
457
Simple diff (without lib)
/**
* Get a diff between two dates
* @param date1 the oldest date
* @param date2 the newest date
* @param timeUnit the unit in which you want the diff
* @return the diff value, in the provided unit
*/
public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
long diffInMillies = date2.getTime() - date1.getTime();
return timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
}
And then can you call:
然后你可以打电话:
getDateDiff(date1,date2,TimeUnit.MINUTES);
to get the diff of the 2 dates in minutes unit.
在分钟单元中得到2个日期的差值。
TimeUnit
is java.util.concurrent.TimeUnit
, a standard Java enum going from nanos to days.
TimeUnit是java . util . concurrent。TimeUnit,从nanos到days的标准Java enum。
Human readable diff (without lib)
public static Map<TimeUnit,Long> computeDiff(Date date1, Date date2) {
long diffInMillies = date2.getTime() - date1.getTime();
List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));
Collections.reverse(units);
Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>();
long milliesRest = diffInMillies;
for ( TimeUnit unit : units ) {
long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
long diffInMilliesForUnit = unit.toMillis(diff);
milliesRest = milliesRest - diffInMilliesForUnit;
result.put(unit,diff);
}
return result;
}
http://ideone.com/5dXeu6
The output is something like Map:{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0}
, with the units ordered.
输出如下图所示:{天=1,小时=3,分钟=46,秒=40,毫秒=0,微秒=0,纳秒=0},单位有序。
You just have to convert that map to an user-friendly string.
您只需将该映射转换为用户友好的字符串。
Warning
The above code snippets compute a simple diff between 2 instants. It can cause problems during a daylight saving switch, like explained in this post. This means if you compute the diff between dates with no time you may have a missing day/hour.
上面的代码片段计算两个瞬间之间的简单差异。它会在日光节约开关期间引起问题,如本文所述。这意味着如果你在没有时间的情况下计算日期之间的差异,你可能会错过一天或一小时。
In my opinion the date diff is kind of subjective, especially on days. You may:
在我看来,日期差异是有点主观的,尤其是在白天。你可以:
-
count the number of 24h elapsed time: day+1 - day = 1 day = 24h
计算24小时运行时间:日+1 -日= 1天= 24小时。
-
count the number of elapsed time, taking care of daylight savings: day+1 - day = 1 = 24h (but using midnight time and daylight savings it could be 0 day and 23h)
计算运行时间的数量,注意日光节约:天+1 -天= 1 = 24小时(但使用午夜时间和夏令时,可能是0天和23小时)
-
count the number of
day switches
, which means day+1 1pm - day 11am = 1 day, even if the elapsed time is just 2h (or 1h if there is a daylight saving :p)计算一天开关的数量,这意味着一天+1个下午-第11am = 1天,即使经过的时间仅为2h(如果有夏令时,则为1h:p)
My answer is valid if your definition of date diff on days match the 1st case
我的回答是有效的,如果你对日期的定义与第一个情况相符
With JodaTime
If you are using JodaTime you can get the diff for 2 instants (millies backed ReadableInstant) dates with:
如果你正在使用JodaTime,你可以用以下两种方式获得diff:
Interval interval = new Interval(oldInstant, new Instant());
But you can also get the diff for Local dates/times:
但你也可以得到当地日期/时间的差异:
// returns 4 because of the leap year of 366 days
new Period(LocalDate.now(), LocalDate.now().plusDays(365*5), PeriodType.years()).getYears()
// this time it returns 5
new Period(LocalDate.now(), LocalDate.now().plusDays(365*5+1), PeriodType.years()).getYears()
// And you can also use these static methods
Years.yearsBetween(LocalDate.now(), LocalDate.now().plusDays(365*5)).getYears()
#3
142
int diffInDays = (int)( (newerDate.getTime() - olderDate.getTime())
/ (1000 * 60 * 60 * 24) )
Note that this works with UTC dates, so the difference may be a day off if you look at local dates. And getting it to work correctly with local dates requires a completely different approach due to daylight savings time.
注意,这适用于UTC日期,因此如果查看本地日期,差异可能是休息日。由于夏令时,要让它在本地日期上正常工作需要一种完全不同的方法。
#4
52
You need to define your problem more clearly. You could just take the number of milliseconds between the two Date
objects and divide by the number of milliseconds in 24 hours, for example... but:
你需要更清楚地定义你的问题。您可以取两个日期对象之间的毫秒数,然后除以24小时内的毫秒数,例如……但是:
- This won't take time zones into consideration -
Date
is always in UTC - 这不会考虑时区——日期总是在UTC
- This won't take daylight saving time into consideration (where there can be days which are only 23 hours long, for example)
- 这就不需要考虑夏令时(例如,有些天可能只有23小时)
- 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?
- 即使在UTC, 8月16日晚上11点到8月18日凌晨2点有多少天?只有27个小时,那意味着有一天吗?或者应该是三天,因为它包含三个日期?
#5
37
Using the java.time framework built into Java 8+:
使用java。Java 8+内置的时间框架:
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime oldDate = now.minusDays(1).minusMinutes(10);
Duration duration = Duration.between(oldDate, now);
System.out.println("ISO-8601: " + duration);
System.out.println("Minutes: " + duration.toMinutes());
Output:
输出:
ISO-8601: PT24H10M
iso - 8601:PT24H10M
Minutes: 1450
分钟:1450
For more info, see the Oracle Tutorial and the ISO 8601 standard.
有关更多信息,请参阅Oracle教程和ISO 8601标准。
#6
34
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
http://joda-time.sourceforge.net/faq.html#datediff
http://joda-time.sourceforge.net/faq.html datediff
#7
30
tl;dr
Convert your obsolete java.util.Date
objects to their replacement, java.time.Instant
. Then calculate the elapsed time as a Duration
.
把过时的java.util。为对象的替换对象(java.time.Instant)设定日期。然后计算运行时间作为持续时间。
Duration d =
Duration.between( // Calculate the span of time between two moments as a number of hours, minutes, and seconds.
myJavaUtilDate.toInstant() , // Convert legacy class to modern class by calling new method added to the old class.
Instant.now() // Capture the current moment in UTC. About two and a half hours later in this example.
)
;
d.toString(): PT2H34M56S
d.toString():PT2H34M56S
d.toMinutes(): 154
d.toMinutes():154
d.toMinutesPart(): 34
d.toMinutesPart():34
ISO 8601 Format: PnYnMnDTnHnMnS
The sensible standard ISO 8601 defines a concise textual representation of a span of time as a number of years, months, days, hours, etc. The standard calls such such a span a duration. The format is PnYnMnDTnHnMnS
where the P
means "Period", the T
separates the date portion from the time portion, and in between are numbers followed by a letter.
合理的标准ISO 8601定义了时间跨度的简明文本表示形式,如年、月、日、小时等。该格式是PnYnMnDTnHnMnS,其中P为“Period”,T将日期部分与时间部分分开,中间是数字,后面是字母。
Examples:
例子:
-
P3Y6M4DT12H30M5S
three years, six months, four days, twelve hours, thirty minutes, and five seconds - 3年,6个月,4天,12小时,30分钟,5秒。
-
PT4H30M
Four and a half hours - PT4H30M 4.5小时
java.time
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date
/java.util.Calendar
classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
java。在Java 8中构建的时间框架,随后取代了麻烦的*ava .util. date / Java .util。日历类。新类的灵感来自于非常成功的Joda-Time框架,它的目标是作为它的继承者,在概念上类似,但是重新架构。由JSR 310定义的。延长了三个额外的项目。看教程。
Moment
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
即时类表示在UTC时间轴上的一个时刻,其分辨率为纳秒(最高为9(9)位小数)。
Instant instant = Instant.now() ; // Capture current moment in UTC.
Best to avoid the legacy classes such as Date
/Calendar
. But if you must inter-operate with old code not yet updated to java.time, convert back and forth. Call new conversion methods added to the old classes. For moving from a java.util.Date
to an Instant
, call Date::toInstant
.
最好避免遗留类,如日期/日历。但是,如果您必须与尚未更新到java的旧代码进行互操作的话。时间,来回转换。调用添加到旧类的新转换方法。从java.util移动。立即约会,打电话日期::立即。
Instant instant = myJavaUtilDate.toInstant() ; // Convert from legacy `java.util.Date` class to modern `java.time.Instant` class.
Span of time
The java.time classes have split this idea of representing a span of time as a number of years, months, days, hours, minutes, seconds into two halves:
java。时间课程将时间跨度分成两部分:年份、月、天、小时、分钟、秒。
Here is an example.
这是一个例子。
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now ( zoneId );
ZonedDateTime future = now.plusMinutes ( 63 );
Duration duration = Duration.between ( now , future );
Dump to console.
转储到控制台。
Both Period
and Duration
use the ISO 8601 standard for generating a String representation of their value.
期间和持续时间都使用ISO 8601标准来生成它们的值的字符串表示形式。
System.out.println ( "now: " + now + " to future: " + now + " = " + duration );
now: 2015-11-26T00:46:48.016-05:00[America/Montreal] to future: 2015-11-26T00:46:48.016-05:00[America/Montreal] = PT1H3M
现在:2015-11-26 t00:46 . 08 -05:00[美国/蒙特利尔]to future: 2015-11-26 t00:46 . 08 -05:00[美国/蒙特利尔]= PT1H3M
Java 9 adds methods to Duration
to get the days part, hours part, minutes part, and seconds part.
Java 9向持续时间添加方法,以获得天数部分、小时部分、分钟部分和秒部分。
You can get the total number of days or hours or minutes or seconds or milliseconds or nanoseconds in the entire Duration.
您可以在整个持续时间内获得天数、小时、分钟、秒、毫秒或纳秒的总数。
long totalHours = duration.toHours();
In Java 9 the Duration
class gets new methods for returning the various parts of days, hours, minutes, seconds, milliseconds/nanoseconds. Call the to…Part
methods: toDaysPart()
, toHoursPart()
, and so on.
在Java 9中,持续时间类获得了新的方法,用于返回日、小时、分钟、秒、毫秒/纳秒的不同部分。调用to…Part方法:toDaysPart(), toHoursPart(),等等。
ChronoUnit
If you only care about a simpler larger granularity of time, such as “number of days elapsed”, use the ChronoUnit
enum.
如果您只关心更简单的更大粒度的时间,例如“已经过的天数”,则使用ChronoUnit enum。
long daysElapsed = ChronoUnit.DAYS.between( earlier , later );
Another example.
另一个例子。
Instant now = Instant.now();
Instant later = now.plus( Duration.ofHours( 2 ) );
…
long minutesElapsed = ChronoUnit.MINUTES.between( now , later );
120
120年
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
java。time框架被构建到Java 8以及以后的版本中。这些类取代了麻烦的旧遗留日期时间类(如java.util)。日期,日历,& SimpleDateFormat。
The Joda-Time project, now in maintenance mode, advises migration to java.time.
现在处于维护模式的Joda-Time项目建议迁移到java.time。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle教程。和搜索堆栈溢出为许多例子和解释。规范是JSR 310。
Where to obtain the java.time classes?
在哪里获得java。时间类?
-
Java SE 8 and SE 9 and later
- Built-in.
- 内置的。
- Part of the standard Java API with a bundled implementation.
- 带有捆绑实现的标准Java API的一部分。
- Java 9 adds some minor features and fixes.
- Java 9添加了一些次要的特性和修复。
- Java SE 8和SE 9,以及后来的内置。带有捆绑实现的标准Java API的一部分。Java 9添加了一些次要的特性和修复。
-
Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- 大部分java。时间功能在三个回端移植到Java 6和7。
- Java SE 6和SE 7大部分的Java。时间功能在三个回端移植到Java 6和7。
-
Android
- The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
- ThreeTenABP项目特别适用于Android。
- See How to use….
- 看到如何使用....
- Android的ThreeTenABP项目特别适用于Android的ThreeTen-Backport(上面提到的)。看到如何使用....
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
三个额外的项目扩展了java。时间和额外的类。这个项目是java.time未来可能增加的一个试验场。您可以在这里找到一些有用的课程,如间隔、年周、年季等。
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. I leave this section intact for history.
更新:Joda-Time项目现在处于维护模式,团队建议迁移到java。时间类。我把这一节完整地留给历史。
The Joda-Time library uses ISO 8601 for its defaults. Its Period
class parses and generates these PnYnMnDTnHnMnS strings.
Joda-Time库默认使用ISO 8601。它的周期类解析并生成这些pnynmndhnmns字符串。
DateTime now = DateTime.now(); // Caveat: Ignoring the important issue of time zones.
Period period = new Period( now, now.plusHours( 4 ).plusMinutes( 30));
System.out.println( "period: " + period );
Renders:
呈现:
period: PT4H30M
#8
22
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小时)。
#9
20
Using millisecond approach can cause problems in some locales.
使用毫秒级的方法可能会在某些地区引起问题。
Lets take, for example, the difference between the two dates 03/24/2007 and 03/25/2007 should be 1 day;
以2007年3月24日和2007年3月25日这两个日期的差值为1天为例;
However, using the millisecond route, you'll get 0 days, if you run this in the UK!
然而,如果你在英国运行这个程序,使用毫秒级的路由,你将得到0天!
/** Manual Method - YIELDS INCORRECT RESULTS - DO NOT USE**/
/* This method is used to find the no of days between the given dates */
public long calculateDays(Date dateEarly, Date dateLater) {
return (dateLater.getTime() - dateEarly.getTime()) / (24 * 60 * 60 * 1000);
}
Better way to implement this is to use java.util.Calendar
更好的实现方法是使用java.util.Calendar
/** Using Calendar - THE CORRECT WAY**/
public static long daysBetween(Calendar startDate, Calendar endDate) {
Calendar date = (Calendar) startDate.clone();
long daysBetween = 0;
while (date.before(endDate)) {
date.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}
#10
19
There are many ways you can find the difference between dates & times. One of the simplest ways that I know of would be:
你可以用很多方法找到日期和时间的不同之处。我所知道的最简单的方法之一是:
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.set(2012, 04, 02);
calendar2.set(2012, 04, 04);
long milsecs1= calendar1.getTimeInMillis();
long milsecs2 = calendar2.getTimeInMillis();
long diff = milsecs2 - milsecs1;
long dsecs = diff / 1000;
long dminutes = diff / (60 * 1000);
long dhours = diff / (60 * 60 * 1000);
long ddays = diff / (24 * 60 * 60 * 1000);
System.out.println("Your Day Difference="+ddays);
The print statement is just an example - you can format it, the way you like.
print语句只是一个示例——您可以按自己喜欢的方式格式化它。
#11
12
Since all the answers here are correct but use legacy java or 3rd party libs like joda or similar, I will just drop another way using new java.time classes in Java 8 and later. See Oracle Tutorial.
由于这里所有的答案都是正确的,但是使用遗留java或第三方libs,如joda或类似的,我将使用新的java放弃另一种方式。Java 8及以后的时间类。看到甲骨文教程。
Use LocalDate
and ChronoUnit
:
使用LocalDate ChronoUnit:
LocalDate d1 = LocalDate.of(2017, 5, 1);
LocalDate d2 = LocalDate.of(2017, 5, 18);
long days = ChronoUnit.DAYS.between(d1, d2);
System.out.println( days );
#12
9
Subtracting the dates in milliseconds works (as described in another post), but you have to use HOUR_OF_DAY and not HOUR when clearing the time parts of your dates:
以毫秒为单位减去日期是有效的(如另一篇文章所描述的),但是你必须使用一小时或一天,而不是一小时来清理你的日期部分:
public static final long MSPERDAY = 60 * 60 * 24 * 1000;
...
final Calendar dateStartCal = Calendar.getInstance();
dateStartCal.setTime(dateStart);
dateStartCal.set(Calendar.HOUR_OF_DAY, 0); // Crucial.
dateStartCal.set(Calendar.MINUTE, 0);
dateStartCal.set(Calendar.SECOND, 0);
dateStartCal.set(Calendar.MILLISECOND, 0);
final Calendar dateEndCal = Calendar.getInstance();
dateEndCal.setTime(dateEnd);
dateEndCal.set(Calendar.HOUR_OF_DAY, 0); // Crucial.
dateEndCal.set(Calendar.MINUTE, 0);
dateEndCal.set(Calendar.SECOND, 0);
dateEndCal.set(Calendar.MILLISECOND, 0);
final long dateDifferenceInDays = ( dateStartCal.getTimeInMillis()
- dateEndCal.getTimeInMillis()
) / MSPERDAY;
if (dateDifferenceInDays > 15) {
// Do something if difference > 15 days
}
#13
8
Take a look at Joda Time, which is an improved Date/Time API for Java and should work fine with Scala.
让我们来看看Joda Time,它是一个改进的Java日期/时间API,应该可以很好地使用Scala。
#14
8
If you don't want to use JodaTime or similar, the best solution is probably this:
如果你不想使用JodaTime或类似的方法,最好的解决方案可能是:
final static long MILLIS_PER_DAY = 24 * 3600 * 1000;
long msDiff= date1.getTime() - date2.getTime();
long daysDiff = Math.round(msDiff / ((double)MILLIS_PER_DAY));
The number of ms per day is not always the same (because of daylight saving time and leap seconds), but it's very close, and at least deviations due to daylight saving time cancel out over longer periods. Therefore dividing and then rounding will give a correct result (at least as long as the local calendar used does not contain weird time jumps other than DST and leap seconds).
每天的毫秒数并不总是相同的(因为夏令时和闰秒),但是非常接近,而且至少由于夏令时的偏差会在更长时间内抵消掉。因此,分割然后舍入将得到正确的结果(至少只要所使用的本地日历不包含除DST和闰秒之外的奇怪时间跳转)。
Note that this still assumes that date1
and date2
are set to the same time of day. For different times of day, you'd first have to define what "date difference" means, as pointed out by Jon Skeet.
注意,这仍然假设date1和date2被设置为一天中的相同时间。对于一天中不同的时间,你首先要定义“日期差异”是什么意思,正如Jon Skeet指出的。
#15
5
Let me show difference between Joda Interval and Days:
让我来展示一下Joda Interval和Days之间的差异:
DateTime start = new DateTime(2012, 2, 6, 10, 44, 51, 0);
DateTime end = new DateTime(2012, 2, 6, 11, 39, 47, 1);
Interval interval = new Interval(start, end);
Period period = interval.toPeriod();
System.out.println(period.getYears() + " years, " + period.getMonths() + " months, " + period.getWeeks() + " weeks, " + period.getDays() + " days");
System.out.println(period.getHours() + " hours, " + period.getMinutes() + " minutes, " + period.getSeconds() + " seconds ");
//Result is:
//0 years, 0 months, *1 weeks, 1 days*
//0 hours, 54 minutes, 56 seconds
//Period can set PeriodType,such as PeriodType.yearMonthDay(),PeriodType.yearDayTime()...
Period p = new Period(start, end, PeriodType.yearMonthDayTime());
System.out.println(p.getYears() + " years, " + p.getMonths() + " months, " + p.getWeeks() + " weeks, " + p.getDays() + "days");
System.out.println(p.getHours() + " hours, " + p.getMinutes() + " minutes, " + p.getSeconds() + " seconds ");
//Result is:
//0 years, 0 months, *0 weeks, 8 days*
//0 hours, 54 minutes, 56 seconds
#16
5
If you need a formatted return String like "2 Days 03h 42m 07s", try this:
如果您需要一个格式化的返回字符串,如“2天03h 42m 07s”,请尝试以下操作:
public String fill2(int value)
{
String ret = String.valueOf(value);
if (ret.length() < 2)
ret = "0" + ret;
return ret;
}
public String get_duration(Date date1, Date date2)
{
TimeUnit timeUnit = TimeUnit.SECONDS;
long diffInMilli = date2.getTime() - date1.getTime();
long s = timeUnit.convert(diffInMilli, TimeUnit.MILLISECONDS);
long days = s / (24 * 60 * 60);
long rest = s - (days * 24 * 60 * 60);
long hrs = rest / (60 * 60);
long rest1 = rest - (hrs * 60 * 60);
long min = rest1 / 60;
long sec = s % 60;
String dates = "";
if (days > 0) dates = days + " Days ";
dates += fill2((int) hrs) + "h ";
dates += fill2((int) min) + "m ";
dates += fill2((int) sec) + "s ";
return dates;
}
#17
4
Check example here http://www.roseindia.net/java/beginners/DateDifferent.shtml This example give you difference in days, hours, minutes, secs and milli sec's :).
这里检查示例http://www.roseindia.net/java/beginners/datedifference .shtml此示例以天、小时、分钟、secs和milli sec:为单位给出不同的示例。
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.");
}
}
#18
4
Use GMT time zone to get an instance of the Calendar, set the time using the set method of Calendar class. The GMT timezone has 0 offset (not really important) and daylight saving time flag set to false.
使用GMT时区获取日历实例,使用Calendar类的set方法设置时间。GMT时区的偏移量为0(并不重要),夏令时标志设置为false。
final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.set(Calendar.YEAR, 2011);
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.DAY_OF_MONTH, 29);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
final Date startDate = cal.getTime();
cal.set(Calendar.YEAR, 2011);
cal.set(Calendar.MONTH, 12);
cal.set(Calendar.DAY_OF_MONTH, 21);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
final Date endDate = cal.getTime();
System.out.println((endDate.getTime() - startDate.getTime()) % (1000l * 60l * 60l * 24l));
#19
4
Following code can give you the desired output:
下面的代码可以给你想要的输出:
String startDate = "Jan 01 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd yyyy");
LocalDate date = LocalDate.parse(startDate, formatter);
String currentDate = "Feb 11 2015";
LocalDate date1 = LocalDate.parse(currentDate, formatter);
System.out.println(date1.toEpochDay() - date.toEpochDay());
#20
4
public static String getDifferenceBtwTime(Date dateTime) {
long timeDifferenceMilliseconds = new Date().getTime() - dateTime.getTime();
long diffSeconds = timeDifferenceMilliseconds / 1000;
long diffMinutes = timeDifferenceMilliseconds / (60 * 1000);
long diffHours = timeDifferenceMilliseconds / (60 * 60 * 1000);
long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
long diffWeeks = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 7);
long diffMonths = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 30.41666666));
long diffYears = (long)(timeDifferenceMilliseconds / (1000 * 60 * 60 * 24 * 365));
if (diffSeconds < 1) {
return "one sec ago";
} else if (diffMinutes < 1) {
return diffSeconds + " seconds ago";
} else if (diffHours < 1) {
return diffMinutes + " minutes ago";
} else if (diffDays < 1) {
return diffHours + " hours ago";
} else if (diffWeeks < 1) {
return diffDays + " days ago";
} else if (diffMonths < 1) {
return diffWeeks + " weeks ago";
} else if (diffYears < 12) {
return diffMonths + " months ago";
} else {
return diffYears + " years ago";
}
}
#21
3
int daysDiff = (date1.getTime() - date2.getTime()) / MILLIS_PER_DAY;
#22
3
Best thing to do is
最好的办法是
(Date1-Date2)/86 400 000
That number is the number of milliseconds in a day.
这个数字是一天的毫秒数。
One date-other date gives you difference in milliseconds.
一个日期-另一个日期以毫秒为单位。
Collect the answer in a double variable.
在双变量中收集答案。
#23
2
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?
您是否满意于以毫秒为单位返回的结果,还是您希望以其他格式返回的问题的一部分?
#24
2
Not using the standard API, no. You can roll your own doing something like this:
不使用标准API。你可以自己做这样的事情:
class Duration {
private final TimeUnit unit;
private final long length;
// ...
}
Or you can use Joda:
或者你可以用Joda:
DateTime a = ..., b = ...;
Duration d = new Duration(a, b);
#25
2
Note: startDate and endDates are -> java.util.Date
注意:startDate和endDates是-> java.util.Date
import org.joda.time.Duration;
import org.joda.time.Interval;
Interval interval = new Interval(startDate.getTime(), endDate.getTime);
Duration period = interval.toDuration();
period.getStandardDays() //gives the number of days elapsed between start and end date
Similar to days, you can also get hours, minutes and seconds
与白天类似,你也可以得到小时、分钟和秒
period.getStandardHours();
period.getStandardMinutes();
period.getStandardSeconds();
#26
2
Just to answer the initial question:
为了回答最初的问题:
Put the following code in a Function like Long getAge(){}
将以下代码放在一个函数中,如Long getAge(){}
Date dahora = new Date();
long MillisToYearsByDiv = 1000l *60l * 60l * 24l * 365l;
long javaOffsetInMillis = 1990l * MillisToYearsByDiv;
long realNowInMillis = dahora.getTime() + javaOffsetInMillis;
long realBirthDayInMillis = this.getFechaNac().getTime() + javaOffsetInMillis;
long ageInMillis = realNowInMillis - realBirthDayInMillis;
return ageInMillis / MillisToYearsByDiv;
The most important here is to work with long numbers when multiplying and dividing. And of course, the offset that Java applies in its calculus of Dates.
这里最重要的是在乘法和除法时使用长数字。当然,Java在其日期演算中应用的偏移量。
:)
:)
#27
1
try this:
试试这个:
int epoch = (int) (new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 00:00:00").getTime() / 1000);
you can edit the string in the parse() methods param.
可以在parse()方法的param中编辑字符串。
#28
1
Since you are using Scala, there is a very good Scala library Lamma. With Lamma you can minus date directly with -
operator
因为您正在使用Scala,所以有一个非常好的Scala库Lamma。有了Lamma,你可以直接用-算符减去日期
scala> Date(2015, 5, 5) - 2 // minus days by int
res1: io.lamma.Date = Date(2015,5,3)
scala> Date(2015, 5, 15) - Date(2015, 5, 8) // minus two days => difference between two days
res2: Int = 7
#29
1
Just use below method with two Date
objects. If you want to pass current date, just pass new Date()
as a second parameter as it is initialised with current time.
使用下面的方法来处理两个日期对象。如果希望传递当前日期,只需将new date()作为第二个参数传递,因为它是用当前时间初始化的。
public String getDateDiffString(Date dateOne, Date dateTwo)
{
long timeOne = dateOne.getTime();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return "dateTwo is " + delta + " days after dateOne";
}
else {
delta *= -1;
return "dateTwo is " + delta + " days before dateOne";
}
}
Also, apart from from number of days, if, you want other parameter difference too, use below snippet,
另外,除了天数之外,如果您还想要其他参数的差异,请使用下面的代码片段,
int year = delta / 365;
int rest = delta % 365;
int month = rest / 30;
rest = rest % 30;
int weeks = rest / 7;
int days = rest % 7;
P.S Code is entirely taken from an SO answer.
P。S的代码完全取自一个SO答案。
#30
1
Earlier versions of Java you can try.
您可以尝试早期版本的Java。
public static String daysBetween(Date createdDate, Date expiryDate) {
Calendar createdDateCal = Calendar.getInstance();
createdDateCal.clear();
createdDateCal.setTime(createdDate);
Calendar expiryDateCal = Calendar.getInstance();
expiryDateCal.clear();
expiryDateCal.setTime(expiryDate);
long daysBetween = 0;
while (createdDateCal.before(expiryDateCal)) {
createdDateCal.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween+"";
}