2

So my Kotlin app is accepting an input String that should be a date in a certain format:

fun haveFun(dateStr: String){
    var formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy")
    var formattedDate = dateStr.format(formatter)
    println(formattedDate)
}

The issue is that no matter which input string I send, it seems that everything is valid and no error is thrown.

The program is cool with whatever text I sent it: 61-Boby-2019 or even I'm not a date

From Java I'm used to some exception to be thrown or an isValid method, but I didn't find such yet in Kotlin

riorio
  • 6,500
  • 7
  • 47
  • 100
  • Does this answer your question? [Java: Check the date format of current string is according to required format or not \[duplicate\]](https://stackoverflow.com/questions/20231539/java-check-the-date-format-of-current-string-is-according-to-required-format-or) See also [my answer here](https://stackoverflow.com/a/58755560/5772882). – Ole V.V. Dec 12 '19 at 18:13

2 Answers2

5

This should work. instead of using the format() use parse() it will throw exception if it fails and handle that at calling side.

@Throws(ParseException::class)
fun haveFun(dateStr: String) {
    var formatter = SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault())
    val date = formatter.parse(dateStr)
    println(date)
}

it will throw error like below:

java.text.ParseException: Unparseable date: "im not date"
vikas kumar
  • 10,447
  • 2
  • 46
  • 52
  • 10
    When the modern `DateTimeFormatter` from java.time is asked about, please don’t bring on the `SimpleDateFormat` class. It’s a notorious troublemaker and long outdated. I strongly discourage using the code from this answer. It also gives poorer validation. Your code gladly accepts `2020-jan-6`, `2020-jan-61`, `6-jan-6 is not a date` and many other incorrect strings. – Ole V.V. Dec 12 '19 at 17:53
2

You are using the wrong methods to format your date.

The method format which you are using (dateStr.format(formatter)) is for formatting the input which takes the current string as a format string as stated here:

fun String.format(vararg args: Any?): String Uses this string as a format string and returns a string obtained by substituting the specified arguments, using the default locale.

You need to do something else in order to achieve what you are looking for.

var formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy")
formatter.format(LocalDate.now()) //12-Dec-2019
Saeed Entezari
  • 3,685
  • 2
  • 19
  • 40