Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

288
Vistas
Kotlin date format change from one to another

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?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda