FreddicMatters
FreddicMatters

Reputation: 431

Convert timestamp with letter T to normal date

I have this time 20220312T153020 from a json and I want to convert it to: 2022-03-12 15:30

I tried this code, but I'm getting an exception.

val fecha = "20220312T153020".replace("T","")
        val formattedDate = SimpleDateFormat("yyyyMMDDHHmmss").format(fecha)
        Log.d("fecha", formattedDate)

Is possible transform that timestamp to human date? I'm trying kotlin code.

thanks so much.

Upvotes: 0

Views: 677

Answers (1)

ocos
ocos

Reputation: 2244

You should use parse(string) to create date object not format(object).

val fecha = "20220312T153020"

// escaping T by quotes 
val sdf = SimpleDateFormat("yyyyMMDD'T'HHmmss")

// attention to parse not format
val formattedDate = sdf.parse(fecha)

Log.d("fecha", formattedDate)

You can find more information here

https://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#parse(java.lang.String)

public Date parse(String source)
           throws ParseException

Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string. 

Upvotes: 1

Related Questions