Home > Mobile >  Kotlin: How to format a list of LocalDateTime to String?
Kotlin: How to format a list of LocalDateTime to String?

Time:03-24

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)
            }
        }
    }
}

CodePudding user response:

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)

CodePudding user response:

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.

CodePudding user response:

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
        }
    }
}
  • Related