旧源系统的历史表有2个关于日期/时间的字段:日期(例如:12/20 / 2017)字符串和时间(14:33:00)字符串。我没有可以使用的时区信息。我正在创建的Web服务正由UI团队使用,该团队希望将此信息用作ISO 8601格式的字符串。我正在使用Java 8.是否创建了ISO 8601格式的String版本,以便在没有时区的情况下返回UI?
答案 0 :(得分:4)
是的,您可以使用DateTimeFormatter ISO_LOCAL_DATE_TIME
进行格式化而不使用时区:
String input = "12/20/2017 14:33:00";
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
LocalDateTime date = LocalDateTime.parse(input, inputFormat);
String output = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(date);
System.out.println(output);
输出:
2017-12-20T14:33:00
答案 1 :(得分:0)
shmosel’s answer是正确的。我会发现在代码中明确指出日期和时间来自不同的字段更清晰,更清晰:
String dateString = "12/20/2017";
String timeString = "14:33:00";
DateTimeFormatter dateInputFormat = DateTimeFormatter.ofPattern("MM/dd/uuuu");
String iso8601DateTimeString = LocalDate.parse(dateString, dateInputFormat)
.atTime(LocalTime.parse(timeString))
.toString();
这会产生2017-12-20T14:33
,符合ISO 8601标准。
您可以使用toString()
代替format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
。有趣的是,它并不总能产生相同的结果:我们现在得到2017-12-20T14:33:00
,即,即使它们为0,也会给出秒数。两个版本都符合ISO 8601标准。