Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Android / Java String DateTime Format, API21

I want convert string datetime to formatted string. e.g "2018-12-14T09:55:00" to "14.12.2018 09:55" as String => Textview.text

how can I do this with kotlin or java for android ?

like image 822
withoutOne Avatar asked Dec 14 '18 13:12

withoutOne


3 Answers

Parse it to LocalDateTime then format it:

LocalDateTime localDateTime = LocalDateTime.parse("2018-12-14T09:55:00");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");
String output = formatter.format(localDateTime);

If this does not work with api21, you can use:

SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
String output = formatter.format(parser.parse("2018-12-14T09:55:00"));

or import ThreeTenABP.

like image 146
xingbin Avatar answered Oct 21 '22 14:10

xingbin


Kotlin API levels 26 or greater:

val parsedDate = LocalDateTime.parse("2018-12-14T09:55:00", DateTimeFormatter.ISO_DATE_TIME)
val formattedDate = parsedDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm"))

Below API levels 26:

val parser =  SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
val formatter = SimpleDateFormat("dd.MM.yyyy HH:mm")
val formattedDate = formatter.format(parser.parse("2018-12-14T09:55:00"))
like image 40
arifng Avatar answered Oct 21 '22 15:10

arifng


If you have a date-time that represents a value in a specific time zone but the zone is not encoded in the date-time string itself (eg, "2020-01-29T09:14:32.000Z") and you need to display this in the time zone you have (eg, CDT)

val parsed = ZonedDateTime.parse("2020-01-29T09:14:32.000Z", DateTimeFormatter.ISO_DATE_TIME).withZoneSameInstant(ZoneId.of("CDT"))

That parsed ZoneDateTime will reflect the time zone given. For example, this date would be something like 28 Jan 2020 at 8:32am.

like image 4
P. Ent Avatar answered Oct 21 '22 14:10

P. Ent