'Kotlin: How to format a list of LocalDateTime to String?
I have succedded to format LocalDateTime to String but now how can I do the same for a list ?
The first function works but the second one doesn't work.
Here my class
class DateFormat {
companion object {
const val PATTERN = "dd-MM-yyyy HH:mm:ss"
fun format(date: LocalDateTime): String {
val formatter = DateTimeFormatter.ofPattern(PATTERN)
return date.format(formatter)
}
fun formatList(date: List<LocalDateTime>): String {
val formatter = DateTimeFormatter.ofPattern(PATTERN)
return date.forEach {
format(formatter)
}
}
}
}
Solution 1:[1]
to return a list of strings you could do this
fun formatList(date: List<LocalDateTime>): List<String> {
val formatter = DateTimeFormatter.ofPattern(PATTERN)
return date.map { it.format(formatter) }
}
or even shorter by referring to your other function like this:
fun formatList(date: List<LocalDateTime>): List<String> {
return date.map { format(it)}
}
or even this to make it super short
fun formatList(date: List<LocalDateTime>) = date.map { format(it)}
Edit: realized you could even write this
fun formatList(date: List<LocalDateTime>) = date.map(::format)
Solution 2:[2]
Based on your second method implementation, you should return list of string instead of single result.
Also I have updated argument for first method to accept DateTimeFormatter, which will be useful while calling from second method.
class DateFormat {
companion object {
const val PATTERN = "dd-MM-yyyy HH:mm:ss"
fun format(date: LocalDateTime, formatter: DateTimeFormatter): String {
return date.format(formatter)
}
fun formatList(date: List<LocalDateTime>): List<String> {
val listResult = listOf<String>()
val formatter = DateTimeFormatter.ofPattern(PATTERN)
date.forEach {
listResult.add(format(formatter))
}
return listResult
}
}
}
Solution 3:[3]
You would need to join your list elements to String. How a "good format" looks like is up to you, the example below will output your dates separated by a "|" - you can use any separator you want (note: this calls your first format function):
fun formatList(date: List<LocalDateTime>): String =
date.joinToString(separator = "|") { format(it) }
EDIT: if you are on Android, note that the usage of DateTimeFormatter requires API level 26.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Sandip Patel |
| Solution 3 |
