Number of days between two dates in Joda-Time
Annoyingly, the withTimeAtStartOfDay answer is wrong, but only occasionally. You want:
Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()
It turns out that "midnight/start of day" sometimes means 1am (daylight savings happen this way in some places), which Days.daysBetween doesn't handle properly.
// 5am on the 20th to 1pm on the 21st, October 2013, Brazil
DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo");
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, BRAZIL);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, BRAZIL);
System.out.println(daysBetween(start.withTimeAtStartOfDay(),
end.withTimeAtStartOfDay()).getDays());
// prints 0
System.out.println(daysBetween(start.toLocalDate(),
end.toLocalDate()).getDays());
// prints 1
Going via a LocalDate
sidesteps the whole issue.
Calculating the number of days between two dates using joda time api
Use this
Days.daysBetween(intdt.toLocalDate(), targetDt.toLocalDate()).getDays()
The LocalDate
class does not store or represent a time or time-zone. Instead, it is a description of the date.
JodaTime: get date(s) between two dates using specific interval
If you could not use Java8 try to use Google Guava:
private static void getDays(DateTime todayDate, DateTime expiryDate, int interval) {
int numberOfDays = Days.daysBetween(new LocalDate(todayDate), new LocalDate(expiryDate)).getDays();
Range<Integer> open = Range.closed(1, numberOfDays/interval);
ImmutableList<Integer> integers = ContiguousSet.create(open, DiscreteDomain.integers()).asList();
FluentIterable.from(integers).transform(new ConvertToDate(interval)).toList().forEach(System.out::println);
}
private static class ConvertToDate implements Function<Integer, DateTime> {
private final int interval;
public ConvertToDate(int interval) {
this.interval = interval;
}
@Override
public DateTime apply(Integer integer) {
return DateTime.now().plusDays(integer* interval);
}
}
I don't know if it is better solution but I find it is easier to read.
How to calculate No of Years, Months and days between two dates using Joda-Time
The reason that your Joda Time code does not work, is because if you don't provide a PeriodType
object, then the standard PeriodType is used. The standard period type defines not only years, months and days to be included in the Period calculation, but also weeks. And you're not displaying the number of weeks, which is 4 in your case. If you write period.getWeeks()
it'll return 4
.
In order to make it work, you have to provide a PeriodType
as third argument to the Period
constructor. If you change the declaration of period
to
Period period = new Period(startDate, endDate, PeriodType.yearMonthDay());
then it'll work. The period calculation will then only use the year, month and day fields.
But
...it is better to migrate to the new Java Date and Time API available in the java.time
package, if you are using Java 8 or above. Don't get me wrong, Joda Time is a very good date and time API. Java 8's date and time API is heavily influenced on Joda Time, because of its quality. Its lead developer is actually the same person, Stephen Colebourne.
But Joda Time is now in maintenance mode, and on its website users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Using Java 8 Date and Time API
DateTimeFormatter f = DateTimeFormatter.ofPattern("dd/MM/yyyy").withLocale(Locale.US);
// expected output 23...2....29
LocalDate startDate = LocalDate.parse("01/09/1995", f);
LocalDate endDate = LocalDate.parse("30/11/2018", f);
Period period = Period.between(startDate, endDate);
Backport to Java 6 and 7; Android support
Most of the java.time
functionality is back-ported to Java 6 and Java 7 in the ThreeTen-Backport project, also led by Stephen Colebourne. Further adapted for earlier Android API levels (below 26) in the ThreeTenABP project. See How to use ThreeTenABP.
Note that there are some differences between Joda Time and the Java Date and Time API. In particular, the Period
class from the Java Date and Time API is less comprehensive. However, the Period
class from the Java Date and Time API provides the functionality which meets your requirement.
I see that this code using java.time
is actually the same as @MaxXFrenzY's. This is not because of copy-paste, that is because the new Java Date and Time API is designed to be both unambiguous and straightforward.
How to calculate difference between two dates in years...etc with Joda-Time
Period
gives you this out of the box.
Period period = new Period(d1, d2);
System.out.print(period.getYears() + " years, ");
System.out.print(period.getMonths() + " months, ");
// ...
To prettify and get a little more control over the output, you can use a PeriodFormatterBuilder
.
How to find difference between two Joda-Time DateTimes in minutes
This will get you the difference between two DateTime objects in milliseconds:
DateTime d1 = new DateTime();
DateTime d2 = new DateTime();
long diffInMillis = d2.getMillis() - d1.getMillis();
How to get number of days between two given dates in Scala
You can't mix java time and joda time. Create the datetime using joda as well.
import org.joda.time.format.DateTimeFormat
import org.joda.time.{Days,Months}
val formatter = DateTimeFormat.forPattern("yyyy-MM-dd")
var start = formatter.parseDateTime("2020-10-01")
var end = formatter.parseDateTime("2020-10-12")
val days = Days.daysBetween(start, end)
val months = Months.monthsBetween(start, end)
Related Topics
How to Iterate Through the Files in a Directory and It's Sub-Directories in Java
Generate/Get Xpath from Xml Node Java
Jformattedtextfield Is Not Properly Cleared
Comparing Strings with == Which Are Declared Final in Java
What Is the "Execute Around" Idiom
How to Specify the Java Compiler Version in a Pom.Xml File
How to Search Google Programmatically Java API
Where Are Static Methods and Static Variables Stored in Java
What Are the Differences Between the Different Saving Methods in Hibernate
Differencebetween Thread.Start() and Thread.Run()
Number of Days Between Two Dates in Joda-Time
Cut Out Image in Shape of Text
What's the Difference Between Concurrenthashmap and Collections.Synchronizedmap(Map)
Hibernate Annotations - Which Is Better, Field or Property Access
Does Java Have Support for Multiline Strings