【发布时间】:2021-07-23 08:07:36
【问题描述】:
我不知道为什么我不能在 Java Android 中将字符串转换为日期。我尝试时出错
错误:
W/System.err: java.text.ParseException: Unparseable date: "Fri Apr 30 00:12:13 GMT+02:00 2021"
我的代码:
String datestr = cursor.getString(cursor.getColumnIndex(UPDATED_AT)); // Fri Apr 30 00:12:13 GMT+02:00 2021
DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.GERMANY);
myDate = dateFormat.parse(datestr);
编辑:
我现在是最新的(我想):
我将所有日期转换为
OffsetDateTime currentDate = OffsetDateTime.now()
这给了我:
2021-04-30T02:14:49.067+02:00
那么如果这个日期是一个字符串,我想把它转换成 OffsetDateTime :
String datestr = cursor.getString(cursor.getColumnIndex(UPDATED_AT)); // 2021-04-30T02:14:49.067+02:00
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").withLocale( Locale.US );
OffsetDateTime myDate = OffsetDateTime.parse( datestr , f );
【问题讨论】:
-
我建议你不要使用
SimpleDateFormat和Date。这些类设计不佳且早已过时,尤其是前者,尤其是出了名的麻烦。而是使用OffsetDateTime或ZonedDateTime和DateTimeFormatter,均来自java.time, the modern Java date and time API。
标签: java android date datetime converters