4

I need a function to find the difference(in number of days)between two dates in "yyyy-mm-dd" format.

val basedate = "1970-01-01"
val currdate = "2015-02-25"
val diff = currdate - basedate

Please suggest.

Govind Singh
  • 15,282
  • 14
  • 72
  • 106
Kundan Kumar
  • 1,974
  • 7
  • 32
  • 54

1 Answers1

9

i think You are searching something like this

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

val startDate = "1970-01-01" 
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val oldDate = LocalDate.parse(startDate, formatter)
val currentDate = "2015-02-25"
val newDate = LocalDate.parse(currentDate, formatter)
println(newDate.toEpochDay() - oldDate.toEpochDay())
Govind Singh
  • 15,282
  • 14
  • 72
  • 106
  • 1
    I am unable to import the packages. Guess its valid for jdk8 whereas I am using 7. Is there any workaround for this ? – Kundan Kumar Feb 25 '15 at 12:27
  • 2
    @KundanKumar, You can use JodaTime API [http://www.joda.org/joda-time/]. Java8 time api is taken from Joda Time only. The syntax will be almost similar between java time api and joda api. – Yadu Krishnan Feb 25 '15 at 13:27
  • @KundanKumar Or use http://www.threeten.org/threetenbp/ to avoid migration later. – Alexey Romanov Feb 26 '15 at 08:54