Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading