0

I get a datetime string from an C# API that looks like this "2021-05-07T08:58:15.993". I am trying to convert it to "2021-05-07 08:58 AM" for my android app. I am using this code:

fun convertStringToDate(stringDate: String): LocalDate? {
        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm ", Locale.ENGLISH)
        val date = LocalDate.parse(stringDate, formatter)
        return date
    }

but it gives me an error of DateTimeParseException "2021-05-07T08:58:15.993" could not be parsed at index 10. Index 10 is the 'T' character. I could just hack it and just remove the T and remove the .993, but, what if the date format changes from the API?

Ibanez1408
  • 4,550
  • 10
  • 59
  • 110
  • I'm not sure I understand. You're trying to parse the input date with the format of the date you want it output in? It might make more sense to parse the date with the format it's actually in then format it with the format you want it in. – Dave Newton May 09 '21 at 02:45
  • I would like to format it on whatever Android would want it. I can settle for just converting that string "2021-05-07T08:58:15.993" to a date. – Ibanez1408 May 09 '21 at 03:28
  • 1
    Parse it in the format you're getting it in. – Dave Newton May 09 '21 at 03:46
  • A `LocalDate` is a date without time of day, so cannot give you the hours and minutes. You need to use `LocalDateTime`. Then you need no formatter for parsing. Just `val date = LocalDateTime.parse(stringDate)`. A `LocalDateTime` cannot have a format, so you may want to format it using the formatter that you have already got and return the resulting string. – Ole V.V. May 09 '21 at 05:34
  • (1) The format will not change from the API. The format is [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601), the international standard. Within the standard they may vary how many decimals they give you on the seconds, though. (2) If they change the format they are giving you, you are going to have to change your program no matter what. – Ole V.V. May 09 '21 at 05:38

0 Answers0