Home > Software design >  Kotlin date format change from one to another
Kotlin date format change from one to another

Time:03-11

I have a list of Dates in format : dd-MM-yyyy

val tripDates = [03-03-2022, 05-03-2002, 23-02-2022]

Now I need to map this list to have not repeatable dates in format only : MM-yyyy

I have tryed to do this as a map:

val calendar = Calendar.getInstance()
val myFormat = "MM-yyyy"
val dateFormat = SimpleDateFormat(myFormat, Locale.US)


        val formattedTrips = tripDates.map {
        calendar.time = it
        val month =  calendar.get(Calendar.MONTH 1).toString()
        val year = calendar.get(Calendar.YEAR).toString()
        val monthAndYear = "$month-$year"
        dateFormat.parse(monthAndYear)
    }

But It doesnt work. I cannot make a new map. Any ideas?

CodePudding user response:

If I understood your question correctly, you want to read dates (as string) and output them to another format (as string).

We need two formatters, one to convert the string (in a given pattern) to date and another to convert the date back to string (in a different pattern).

Java 7

import java.text.SimpleDateFormat

val fullDatePattern = "dd-MM-yyyy"
val monthYearPattern = "MM-yyyy"

val fullDateFormatter = SimpleDateFormat(fullDatePattern)
val monthYearFormatter = SimpleDateFormat(monthYearPattern)

val dates = listOf(
  "03-03-2022",
  "05-03-2002",
  "23-02-2022",
)

dates.map { dateString ->
  monthYearFormatter.format(fullDateFormatter.parse(dateString))
}

I think it's worth mentioning that SimpleDateFormat is not thread-safe, so be careful.

Java 8

import java.time.LocalDate
import java.time.format.DateTimeFormatter

val fullDatePattern = "dd-MM-yyyy"
val monthYearPattern = "MM-yyyy"

val fullDateFormatter = DateTimeFormatter.ofPattern(fullDatePattern)
val monthYearFormatter = DateTimeFormatter.ofPattern(monthYearPattern)

val dates = listOf(
  "03-03-2022",
  "05-03-2002",
  "23-02-2022",
)

dates.map { dateString ->
  LocalDate
    .parse(dateString, fullDateFormatter)
    .format(monthYearFormatter)
}

Output for both examples above: [03-2022, 03-2002, 02-2022]

And if you want to remove duplicated dates, you can use the function distinct.

  • Related