简体   繁体   中英

how to check leap year in scala

I have a date in string format . i want to check whether the date is correct according to month or not. eg 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") .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM