2

I have a date in string format . i want to check whether the date is correct according to month or not. e.g january shouldnot exceed by 31.

Hence 32/1/2016 shold be invalid date.

def check(date:String,format:String)={
  val splittedDate=date.split("/")
  val res=(fullDay(2).toInt) <= LocalDate.of(fullDay(0).toInt,fullDay(1).toInt,fullDay(2).toInt).lengthOfMonth()
  res
}

It will work fine if we call like check("2015/4/5","yyyy/mm/dd"). but don't work with check("2015/4/5","dd/yyyy/mm").

Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57
user6207861
  • 51
  • 1
  • 6
  • 3
    I don't know scala so the syntax is not familiar to me but I have two questions: What does 32/1/2016 have to do with a leap year? And why should `check("2015/4/5","dd/yyyy/mm")` work if the pattern doesn't match the provided date? – Thomas Apr 19 '16 at 09:16
  • Possible duplicate of [Scala/Lift check if date is correctly formatted](http://stackoverflow.com/questions/5982484/scala-lift-check-if-date-is-correctly-formatted) – airudah Apr 19 '16 at 09:24
  • because user can pass any format to check whether date is correct or not. – user6207861 Apr 19 '16 at 09:32
  • 1
    january donot have day 32 so it should give an error message – user6207861 Apr 19 '16 at 09:33
  • I would suggest working with Joda time. it will simplify date processing in scala – Zee Apr 19 '16 at 13:19
  • Don't re-implement this wheel; see (and use) the question linked to by @RobertUdah – The Archetypal Paul Apr 19 '16 at 14:41

1 Answers1

1

Just use java.time, to parse/create date.

If your date is invalid, you will get an exception. For example:

scala> LocalDate.of(2016, 2, 31)
java.time.DateTimeException: Invalid date 'FEBRUARY 31'
  at java.time.LocalDate.create(LocalDate.java:431)
  at java.time.LocalDate.of(LocalDate.java:269)
  ... 33 elided

scala> LocalDate.of(2016, 2, 30)
java.time.DateTimeException: Invalid date 'FEBRUARY 30'
  at java.time.LocalDate.create(LocalDate.java:431)
  at java.time.LocalDate.of(LocalDate.java:269)
  ... 33 elided

scala> LocalDate.of(2016, 2, 29)
res15: java.time.LocalDate = 2016-02-29

scala> LocalDate.of(2015, 2, 29)
java.time.DateTimeException: Invalid date 'February 29' as '2015' is not a leap year
  at java.time.LocalDate.create(LocalDate.java:429)
  at java.time.LocalDate.of(LocalDate.java:269)
  ... 33 elided
Łukasz
  • 8,555
  • 2
  • 28
  • 51