-8

I want to know the number of days between two dates. When I use the following code it raises an error. How do I fix it?

import org.joda.time.{DateTime, Days}

val start = "2018-10-01 00:00:00"
val end= "2018-10-12 00:00:00"

val from = DateTime.parse(start)
val to = DateTime.parse(end)

println(from + "<>" + to)

println("Number of days between 2 period: " + Days.daysBetween(from, to).getDays)

ERROR:

java.lang.IllegalArgumentException: Invalid format: "2018-10-01 00:00:00" is malformed at " 00:00:00"
Boann
  • 48,794
  • 16
  • 117
  • 146
Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193
  • 2
    You have parsing error, you should pass right DateTimeFormatter for your date strings. – mkUltra Jan 17 '19 at 10:13
  • 1
    Please read the error message carefully. What do you think does this error message mean? – Jesper Jan 17 '19 at 10:13
  • Possible duplicate of [Difference in days between two dates in Java?](https://stackoverflow.com/questions/3299972/difference-in-days-between-two-dates-in-java) – C4stor Jan 18 '19 at 14:23

3 Answers3

2

joda.time is old and outdated. Use java.time.

import java.time.LocalDate
import java.time.temporal.ChronoUnit.DAYS

DAYS.between(LocalDate.parse("2018-10-01")
            ,LocalDate.parse("2018-10-12"))  //res0: Long = 11
jwvh
  • 50,871
  • 7
  • 38
  • 64
0

You can try something like this

import java.time.LocalDate 
import java.time.format.DateTimeFormatter


val start = "2018-10-01"
val end= "2018-10-12"


val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val oldDate = LocalDate.parse(start, formatter)

val newDate = LocalDate.parse(end, formatter)
println(newDate.toEpochDay() - oldDate.toEpochDay())
NPE
  • 429
  • 2
  • 16
0

Finally I found solution:

val format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")

val from = format.parseDateTime("2018-10-01 00:00:00")
val to = format.parseDateTime("2018-10-12 00:00:00")

println("Number of days between 2 period: " + Days.daysBetween(from, to).getDays)
Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193