[英]In Java, Can I Convert A Date and Time To An ISO 8601 formatted String Without A Timezone?
A history table of an old source system has 2 fields regarding date/time: a date (ex: 12/20/2017) String and a time (14:33:00) String. 旧源系统的历史记录表具有2个有关日期/时间的字段:日期(例如:12/20/2017)字符串和时间(14:33:00)字符串。 I have no timezone information I can use.
我没有可以使用的时区信息。 The web service I'm creating is being consumed by a UI team which wants this information as an ISO 8601 formatted String.
UI团队正在使用我正在创建的Web服务,该团队希望此信息为ISO 8601格式的String。 I'm using Java 8. Is creating an ISO 8601 formatted String version to return to the UI possible without a timezone?
我正在使用Java8。是否可以创建没有时区的ISO 8601格式的String版本以返回UI?
Yes, you can use DateTimeFormatter ISO_LOCAL_DATE_TIME
to format without the time zone: 是的,您可以使用
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);
Output: 输出:
2017-12-20T14:33:00
shmosel's answer is correct. shmosel的答案是正确的。 I would find it clearer and cleaner to make explicit in the code that the date and the time come from separate fields:
我会发现在代码中明确指出日期和时间来自不同的字段会更加清晰明了:
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();
This produces 2017-12-20T14:33
, which is ISO 8601 compliant. 这将产生符合ISO 8601的
2017-12-20T14:33
。
Instead of toString()
you may use format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
. 可以使用
format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
代替toString()
format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
。 Funnily it doesn't always produce the same result: we now get 2017-12-20T14:33:00
, that is, the seconds are given even when they are 0. Both versions are ISO 8601 compliant. 有趣的是,它并不总是产生相同的结果:我们现在得到
2017-12-20T14:33:00
,即,即使它们是0,也给出秒。这两个版本都符合ISO 8601。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.