SimpleDateFormat wrong result Kotlin

Issue

My input in this case is 2012-09-28 but I receive 01/01/2011

I would like to receive 09/28/2012

main(){
 val scan  Scanner(System.`in`)
    val originalFormat: DateFormat  SimpleDateFormat("YYYY-MM-DD", Locale.ENGLISH)
    val targetFormat: DateFormat  SimpleDateFormat("MM/DD/YYYY")
    val date  originalFormat.parse(scan.next())
    val formattedDate  targetFormat.format(date)
    println(formattedDate)
}

What is my code missing?

Solution

The modern API for parsing and formatting date and time is java.time, which was introduced with Java 8. You can either import the ThreeTenAbp or use Android API Desugaring in order to make it work in Android API versions below 26.

The following example uses java.time and considers the input of the two different formats you posted (one in your question and one as a comment to the first answer).

import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Scanner

fun main() {
    val scan  Scanner(System.`in`)
    // create a formatter that parses the two different EXPECTED input formats
    val inputFormatter  DateTimeFormatter.ofPattern("[uu-MM-dd][uuuu-MM-dd]");
    // parse the input
    val localDate: LocalDate  LocalDate.parse(scan.next(), inputFormatter)
    // define a formatter with the desired output format
    val targetFormat: DateTimeFormatter  DateTimeFormatter.ofPattern("MM/dd/uuuu")
    // then create a String with the desired output format
    val formattedDate: String  localDate.format(targetFormat)
    // and print it
    println(formattedDate)
}

The result for the inputs 12-09-30 or 2012-09-30 is 09/30/2012 in both cases.

Answered By – deHaar

Leave a Comment