/** 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);
}
更好的实现方法是使用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;
}
import java.util.*;
int syear = 2000;
int eyear = 2000;
int smonth = 2;//Feb
int emonth = 3;//Mar
int sday = 27;
int eday = 1;
Date startDate = new Date(syear-1900,smonth-1,sday);
Date endDate = new Date(eyear-1900,emonth-1,eday);
int difInDays = (int) ((endDate.getTime() - startDate.getTime())/(1000*60*60*24));
/**
* 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);
}
public static Map<TimeUnit,Long> computeDiff(Date date1, Date date2) {
long diffInMillies = date2.getTime() - date1.getTime();
//create the list
List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));
Collections.reverse(units);
//create the result map of TimeUnit and difference
Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>();
long milliesRest = diffInMillies;
for ( TimeUnit unit : units ) {
//calculate difference in millisecond
long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
long diffInMilliesForUnit = unit.toMillis(diff);
milliesRest = milliesRest - diffInMilliesForUnit;
//put the result in the map
result.put(unit,diff);
}
return result;
}
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()
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.
)
;
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 );
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
import org.joda.time.Duration;
import org.joda.time.Interval;
// Use .getTime() unless it is a joda DateTime object
Interval interval = new Interval(startDate.getTime(), endDate.getTime());
Duration period = interval.toDuration();
//gives the number of days elapsed between start and end date.
period.getStandardDays();
public static boolean isLeapYear (int year) {
//Every 4. year is a leap year, except if the year is divisible by 100 and not by 400
//For example 1900 is not a leap year but 2000 is
boolean result = false;
if (year % 4 == 0) {
result = true;
}
if (year % 100 == 0) {
result = false;
}
if (year % 400 == 0) {
result = true;
}
return result;
}
2)
public static int daysGoneSince (int yearZero, int year, int month, int day) {
//Calculates the day number of the given date; day 1 = January 1st in the yearZero
//Validate the input
if (year < yearZero || month < 1 || month > 12 || day < 1 || day > 31) {
//Throw an exception
throw new IllegalArgumentException("Too many or too few days in month or months in year or the year is smaller than year zero");
}
else if (month == 4 || month == 6 || month == 9 || month == 11) {//Months with 30 days
if (day == 31) {
//Throw an exception
throw new IllegalArgumentException("Too many days in month");
}
}
else if (month == 2) {//February 28 or 29
if (isLeapYear(year)) {
if (day > 29) {
//Throw an exception
throw new IllegalArgumentException("Too many days in month");
}
}
else if (day > 28) {
//Throw an exception
throw new IllegalArgumentException("Too many days in month");
}
}
//Start counting days
int days = 0;
//Days in the target month until the target day
days = days + day;
//Days in the earlier months in the target year
for (int i = 1; i < month; i++) {
switch (i) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
days = days + 31;
break;
case 2:
days = days + 28;
if (isLeapYear(year)) {
days = days + 1;
}
break;
case 4: case 6: case 9: case 11:
days = days + 30;
break;
}
}
//Days in the earlier years
for (int i = yearZero; i < year; i++) {
days = days + 365;
if (isLeapYear(i)) {
days = days + 1;
}
}
return days;
}
3)
public static int dateDiff (int startYear, int startMonth, int startDay, int endYear, int endMonth, int endDay) {
int yearZero;
//daysGoneSince presupposes that the first argument be smaller or equal to the second argument
if (10000 * startYear + 100 * startMonth + startDay > 10000 * endYear + 100 * endMonth + endDay) {//If the end date is earlier than the start date
yearZero = endYear;
}
else {
yearZero = startYear;
}
return daysGoneSince(yearZero, endYear, endMonth, endDay) - daysGoneSince(yearZero, startYear, startMonth, startDay);
}
import scala.concurrent.duration._
val diff = (System.currentTimeMillis() - oldDate.getTime).milliseconds
val diffSeconds = diff.toSeconds
val diffMinutes = diff.toMinutes
val diffHours = diff.toHours
val diffDays = diff.toDays
public boolean isWithin30Days(Calendar queryCalendar) {
// 1. Take the date you are checking, and roll it back N days
Calendar queryCalMinus30Days = Calendar.getInstance();
queryCalMinus30Days.setTime(queryCalendar.getTime());
queryCalMinus30Days.add(Calendar.DATE, -30); // subtract 30 days from the calendar
// 2. Get respective milliseconds for the two Calendars: now & queryCal minus N days
long nowL = Calendar.getInstance().getTimeInMillis();
long queryCalMinus30DaysL = queryCalMinus30Days.getTimeInMillis();
// 3. if nowL is still less than the queryCalMinus30DaysL, it means queryCalendar is more than 30 days into future
boolean isWithin30Days = nowL >= queryCalMinus30DaysL;
return isWithin30Days;
}
public static long calculateDifferenceInDays(Date start, Date end, Locale locale) {
Calendar cal = Calendar.getInstance(locale);
cal.setTime(start);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long startTime = cal.getTimeInMillis();
cal.setTime(end);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long endTime = cal.getTimeInMillis();
// calculate the offset if one of the dates is in summer time and the other one in winter time
TimeZone timezone = cal.getTimeZone();
int offsetStart = timezone.getOffset(startTime);
int offsetEnd = timezone.getOffset(endTime);
int offset = offsetEnd - offsetStart;
return TimeUnit.MILLISECONDS.toDays(endTime - startTime + offset);
}
import java.util.Date;
import java.util.concurrent.TimeUnit;
public static long getDaysBetween(Date date1, Date date2, boolean includeEndDate) {
long millisInDay = 60 * 60 * 24 * 1000;
long difference = Math.abs(date1.getTime() - date2.getTime());
long add = millisInDay - (difference % millisInDay);//is used to calculate true number of days, because by default hours, minutes are also counted
return TimeUnit.MILLISECONDS.toDays(difference + add) + (includeEndDate ? 1 : 0);
}
测试:
Date date1 = new Date(121, Calendar.NOVEMBER, 27); //2021 Nov 27
Date date2 = new Date(121, Calendar.DECEMBER, 29); //2021 Dec 29
System.out.println( getDaysBetween(date1, date2, false) ); //32 days difference
System.out.println( getDaysBetween(date1, date2, true) ); //33 days difference