Home > Back-end >  SimpleDateFormat wrong result Kotlin
SimpleDateFormat wrong result Kotlin

Time:09-17

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?

CodePudding user response:

If you want to use a modern API for parsing and formatting date and time, use java.time, which was introduced in 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 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.

CodePudding user response:

Colud you try this way?

fun main() {
    val scan = Scanner(System.`in`)
    val originalFormat = SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH)
    val targetFormat = SimpleDateFormat("MM/dd/yyyy")
    val date = originalFormat.parse(scan.next())
    val formattedDate = targetFormat.format(date)
    println(formattedDate)
}

d is a day in the month. (ex_10)
D is a day in the year. (ex_189)

y is the year. (ex_1996; 96)
Y is week year. (ex_2009; 09)

CodePudding user response:

Use yyyy instead of YYYY and dd instead of DD.

DD is the day of year while dd is the day of month.

YYYY is the week year and yyyy is the regular year.

https://developer.android.com/reference/java/text/SimpleDateFormat?hl=en

  • Related