繁体   English   中英

在Java中,是否可以将日期和时间转换为没有时区的ISO 8601格式的字符串?

[英]In Java, Can I Convert A Date and Time To An ISO 8601 formatted String Without A Timezone?

旧源系统的历史记录表具有2个有关日期/时间的字段:日期(例如:12/20/2017)字符串和时间(14:33:00)字符串。 我没有可以使用的时区信息。 UI团队正在使用我正在创建的Web服务,该团队希望此信息为ISO 8601格式的String。 我正在使用Java8。是否可以创建没有时区的ISO 8601格式的String版本以返回UI?

是的,您可以使用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

shmosel的答案是正确的。 我会发现在代码中明确指出日期和时间来自不同的字段会更加清晰明了:

    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();

这将产生符合ISO 8601的2017-12-20T14:33

可以使用format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)代替toString() format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) 有趣的是,它并不总是产生相同的结果:我们现在得到2017-12-20T14:33:00 ,即,即使它们是0,也给出秒。这两个版本都符合ISO 8601。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM