Kotlin Android / Java 字符串日期时间格式,API21
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53781154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Kotlin Android / Java String DateTime Format, API21
提问by withoutOne
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
我想将字符串日期时间转换为格式化字符串。例如“2018-12-14T09:55:00”到“14.12.2018 09:55”作为字符串=> Textview.text
how can I do this with kotlin or java for android ?
我怎样才能用 kotlin 或 java for android 做到这一点?
采纳答案by xingbin
Parse it to LocalDateTime
then format it:
解析它LocalDateTime
然后格式化它:
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:
如果这不适用于 api21,您可以使用:
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.
或导入 ThreeTenABP。
回答by arifng
Kotlin API levels 26 or greater:
Kotlin API 级别 26 或更高:
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:
API 级别 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"))
回答by P. Ent
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)
如果您有一个表示特定时区中的值的日期时间,但该区域未在日期时间字符串本身中编码(例如,“2020-01-29T09:14:32.000Z”)并且您需要显示这是您拥有的时区(例如,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.
这parsed
ZoneDateTime将反映给定的时区。例如,此日期类似于 2020 年 1 月 28 日上午 8:32。