` `(new java.util.Date()).getTime() - oldDate.getTime()` `

` `Interval interval = new Interval(oldTime, new Instant());` `

# 简单差异（无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); }` `

` `getDateDiff(date1,date2,TimeUnit.MINUTES);` `

`TimeUnit``java.util.concurrent.TimeUnit` ，这是一个从纳米级到数天级的标准Java枚举。

# 人类可读的差异（没有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; }` `

# 警告

• 统计24小时经过时间的数量：天+ 1天= 1天= 24小时

• 计算经过的时间，照顾夏令时：天+ 1天= 1 = 24小时（但是使用午夜时间和夏令时可以是0天和23小时）

• 请计算`day switches` ，即即使经过的时间仅为2小时（或者如果有夏令时，则为1小时），即date+ 11下午 – 上午11时= 1天。

# 随着JodaTime

` `Interval interval = new Interval(oldInstant, new Instant());` `

` `// 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()` `
` `int diffInDays = (int)( (newerDate.getTime() - olderDate.getTime()) / (1000 * 60 * 60 * 24) )` `

• 这不会考虑时区 – `Date`始终是UTC
• 这不会考虑夏令时（例如可能只有23小时的日子）
• 即使在UTC内，8月16日晚上11点到8月18日凌晨2点还有多less天？ 这只有27个小时，这是否意味着有一天？ 还是应该是三天，因为它包括三个date？
` `Days d = Days.daysBetween(startDate, endDate); int days = d.getDays();` `

` `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());` `

ISO-8601：PT24H10M

# TL;博士

` `Duration d = Duration.between( then , Instant.now() ); // Two and a half hours ago.` `

d.toString（）：PT2H34M56S

d.toMinutes（）：154

d.toMinutesPart（）：34

# ISO 8601格式： `PnYnMnDTnHnMnS`

• `P3Y6M4DT12H30M5S`
三年，六个月，四天，十二小时，三十分钟和五秒钟
• `PT4H30M`
四个半小时

# java.time

java.time类已经将这种将时间跨度表示为几年，几个月，几天，几小时，几分钟，几秒的想法分成两部分：

• `Period`为几年，几个月，几天
• `Duration`几天，几小时，几分钟，几秒钟

` `ZoneId zoneId = ZoneId.of ( "America/Montreal" ); ZonedDateTime now = ZonedDateTime.now ( zoneId ); ZonedDateTime future = now.plusMinutes ( 63 ); Duration duration = Duration.between ( now , future );` `

`Period``Duration`使用ISO 8601标准来生成其值的string表示。

` `System.out.println ( "now: " + now + " to future: " + now + " = " + duration );` `

2015-11-26T00：46：48.016-05：00 [America / Montreal] to future：2015-11-26T00：46：48.016-05：00 [America / Montreal] = PT1H3M

Java 9增加了`Duration`方法来获取date部分，小时部分，分钟部分和秒部分。

` `long totalHours = duration.toHours();` `

# `ChronoUnit`

` `long daysElapsed = ChronoUnit.DAYS.between( earlier , later );` `

` `Instant now = Instant.now(); Instant later = now.plus( Duration.ofHours( 2 ) ); … long minutesElapsed = ChronoUnit.MINUTES.between( now , later );` `

120

# 关于java.time

java.time框架内置于Java 8及更高版本中。 这些类取代了麻烦的旧的遗留date时间类，如`java.util.Date``Calendar``SimpleDateFormat`

Joda-Time项目现在处于维护模式 ，build议迁移到java.time。

• Java SE 8SE 9及更高版本
• 内置。
• 带有捆绑实现的标准Java API的一部分。
• Java 9增加了一些小function和修复。
• Java SE 6SE 7
• 大部分的java.timefunction都被移植到了ThreeTen-Backport中的 Java 6＆7中。
• Android的
• ThreeTenABP项目专门针对Android，采用了ThreeTen-Backport （上文提到）。
• 请参阅如何使用…。

ThreeTen-Extra项目将java.time扩展到其他类。 这个项目是未来可能增加java.time的一个试验场。 你可能会在这里find一些有用的类，比如`Interval``YearWeek``YearQuarter` 等等 。

# 乔达时间

` `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 );` `

` `period: PT4H30M` `

` `System.currentTimeMillis() - oldDate.getTime()` `

` `/** 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); }` `

` `/** 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; }` `

` ` 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);` `

` `final static long MILLIS_PER_DAY = 24 * 3600 * 1000; long msDiff= date1.getTime() - date2.getTime(); long daysDiff = Math.round(msDiff / ((double)MILLIS_PER_DAY));` `

` `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 }` `

` `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 );` `

` `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` `

` `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; }` `
` `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."); } }` `

` ` 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));` `

` `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());` `
` `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"; } }` `
` `int daysDiff = (date1.getTime() - date2.getTime()) / MILLIS_PER_DAY;` `

` `(Date1-Date2)/86 400 000` `

` `class Duration { private final TimeUnit unit; private final long length; // ... }` `

` `DateTime a = ..., b = ...; Duration d = new Duration(a, b);` `

` `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` `

` `period.getStandardHours(); period.getStandardMinutes(); period.getStandardSeconds();` `

` `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;` `

🙂

` `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"; } }` `

` `int year = delta / 365; int rest = delta % 365; int month = rest / 30; rest = rest % 30; int weeks = rest / 7; int days = rest % 7;` `

PS代码完全取自一个SO回答。

` `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.

Since you are using Scala, there is a very good Scala library Lamma . With Lamma you can minus date directly with `-` operator

` `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` `

Earlier versions of Java you can try.

` ` 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+""; }` `