尝试更改字符串的日期格式,但获取DateTimeException:
String oldDate = "2018-12-18T17:04:56+00:00";
String outputFormat = "DD-MM";
try {
Instant instant = Instant.parse(oldDate);
LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
return localDateTime.format(DateTimeFormatter.ofPattern(outputFormat);
} catch (DateTimeException | IllegalArgumentException e) {
Log.e("Error", e.getLocalizedMessage());
return "";
}我收到的错误是:无法在索引19处解析文本'2018-12-18T17:04:56+00:00‘
我使用的是com.jakewharton.trietenabp:threetenabp:1.1.1,因为我不能使用Java 8类
发布于 2018-12-19 06:11:14
tl;dr
OffsetDateTime.parse( // Represent a moment, a date with time-of-day in the context of an offset-from-UTC (some number of hours-minutes-seconds).
"2018-12-18T17:04:56+00:00" // Input string in standard ISO 8601 format, with an indicator of an offset-from-UTC of zero hours and zero minutes, meaning UTC itself.
) // Returns an `OffsetDateTime` object.
.atZoneSameInstant( // Adjust our moment from UTC to the wall-clock time used by the people of a particular region (a time zone).
ZoneId.systemDefault() // Using the JVM’s current default time zone. NOTE: this default can change at any moment during runtime. If important, confirm with the user.
) // Returns a `ZonedDateTime` object.
.toString() // Generate text in standard ISO 8601 format wisely extended by appending the name of the zone in square brackets. Returns a `String` object.2018-12-18T09:04:56-08:00美国/洛杉矶
详细信息
以下是使用项目的示例Java代码,该项目由为26版本之前的Android扩展。
import org.threeten.bp.*;错误的格式化程序
Instant.parse命令使用DateTimeFormatter.ISO_INSTANT格式化程序。该格式化程序期望末尾的Z指示UTC。
Instant类是java.time框架的基本构建块类。要获得更大的灵活性,请使用OffsetDateTime。它的默认格式化程序DateTimeFormatter.ISO_OFFSET_DATE_TIME可以处理您的输入。
String input = "2018-12-18T17:04:56+00:00";
OffsetDateTime odt = OffsetDateTime.parse( input );odt.toString():2018-12-18T17:04:56Z
错误的班级
不要使用LocalDateTime来跟踪某个时刻。这个类故意缺少任何time zone或offset-from-UTC的概念。它只是一个日期和时间。因此,它不能代表一个时刻,永远不会是时间线上的一个点。取而代之的是,这个类代表了26-27小时范围内的潜在时刻,即全球各地的时区范围。
要跟踪某个时刻,只需使用:
在协调世界时的时刻,总是UTC.
一个日期,一天中的某个时间,带有与UTC的偏移量。偏移量仅仅是小时-分钟-秒的数字,没有more.
通过特定地区、时区的人们所使用的挂钟时间所看到的时刻。区域是对特定区域中使用的偏移的过去、现在和未来更改的历史记录。
要将OffsetDateTime从协调世界时调整为某个时区,请应用ZoneId以获取ZonedDateTime。
ZoneId z = ZoneId.systemDefault() ; // If important, confirm the zone with user rather than depending on the JVM’s current default zone.
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;zdt.toString():2018-12-18T09:04:56-08:00美国/洛杉矶
根据这些结果,我们看到UTC的下午5点在北美大部分西海岸同时是上午9点。-08:00的差异意味着在这一天,西海岸比协调世界时晚8小时。
关于java.time
框架内置于Java8和更高版本中。这些类取代了麻烦的旧legacy日期时间类,如java.util.Date、Calendar和SimpleDateFormat。
现在在maintenance mode中的项目建议迁移到java.time类。
要了解更多信息,请参阅。和搜索堆栈溢出,以获得许多示例和解释。规范为JSR 310。
您可以直接与数据库交换java.time对象。使用与JDBC 4.2或更高版本兼容的JDBC driver。不需要字符串,也不需要java.sql.*类。
从哪里获取java.time类?
中的
项目使用额外的类扩展了java.time。这个项目是未来可能添加到java.time中的试验场。您可能会在这里找到一些有用的类,如Interval、YearWeek、YearQuarter和more。
https://stackoverflow.com/questions/53838449
复制相似问题