Reputation: 148
i tried to get all date between two given dates , but unable to get.
I have tried like this.
val dateformat = new SimpleDateFormat("yyyy-MM-dd")
var start = dateformat.parse("2020-10-01")
var end = dateformat.parse("2020-10-12")
val days = Days.daysBetween(start, end)
val months = Months.monthsBetween(start, end)
But i am getting daysBetween not found?
Edit: my imports are:
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Months;
Upvotes: 0
Views: 2745
Reputation: 86130
For the sake of completeness here’s the java.time version of the same code. java.time is the modern Java date and time API and the successor of Joda-Time. You will have to translate from my Java code yourself, though.
import java.time.temporal.ChronoUnit;
import java.time.LocalDate;
LocalDate start = LocalDate.parse("2020-10-01");
LocalDate end = LocalDate.parse("2020-10-12");
long days = ChronoUnit.DAYS.between(start, end);
long months = ChronoUnit.MONTHS.between(start, end);
System.out.format("Between %s and %s are %d days or %d months%n",
start, end, days, months);
Output:
Between 2020-10-01 and 2020-10-12 are 11 days or 0 months
The Joda-Time home page says:
Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to
java.time
(JSR-310).
But i am getting daysBetween not found?
It’s not that Scala cannot find Days.daysBetween()
. Your start
and end
have type Date
, and what the message means is that Scala cannot find a daysBetween
method that accepts two Date
arguments. Instead you will need to pass two objects of type ReadableInstant
(or ReadablePartial
, but that’s a different story). Since Joda’s own DateTime
class implements the ReadableInstant
interface, you’ll be fine with two of those as shown in the other answer.
Upvotes: 6
Reputation: 42332
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)
Upvotes: 2