【问题标题】:How to use DateTimeFormatter to get time only?如何使用 DateTimeFormatter 仅获取时间?
【发布时间】:2020-07-21 07:11:27
【问题描述】:

我正在制作约会应用程序,并试图仅将约会时间填入组合框。到目前为止,我只能获得日期,但现在我无法获得时间。它在组合框中显示为 yyyy-MM-dd HH:mm。有问题的代码是最后两个语句。 modifyDate 仅成功打印日期,但我似乎无法弄清楚如何将日期分开并仅​​打印时间。我试图用 HH:mm 创建另一个 DateTimeFormatter ,但这没有用。非常感谢!

这个 setAppointment 将现有约会中的数据放入修改屏幕:

public void setAppointment(Appointment appointment, int index) {
    selectedAppointment = appointment;
    selectedIndex = index;

    Appointment newAppointment = (Appointment) appointment;

    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    this.modifyContactNameText.setText(newAppointment.getContact());
    this.modifyTitleText.setText((newAppointment.getTitle()));
    this.modifyURLText.setText((newAppointment.getUrl()));
    this.modifyTypeText.setText((newAppointment.getType()));
    this.modifyDescriptionComboBox.setValue((newAppointment.getDescription()));
    this.modifyLocationComboBox.setValue((newAppointment.getLocation()));
    this.modifyDate.setValue(LocalDate.parse(newAppointment.getStart(), format));
    this.modifyStartComboBox.getSelectionModel().select(newAppointment.getStart(), format));
    this.modifyEndComboBox.getSelectionModel().select(newAppointment.getEnd(), format));

【问题讨论】:

  • newAppointment.getStart() 返回什么?
  • 它将从数据库中返回一个日期+时间。类似于“2020-03-27 11:00”,getEnd 将返回相同的日期,但结束时间。
  • 您不应该在 Appointment 类中将开始和结束时间保留为 String。保留正确的日期时间对象,例如 ZonedDateTimeInstantLocalDateTime(取决于具体要求)。

标签: java date java-8 java-time


【解决方案1】:

是的,您需要将String 转换为LocalDateTime,然后使用另一个格式化程序提取时间部分:

...
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("HH:mm");
String time = LocalDateTime.parse(newAppointment.getStart(), format)
             .format(timeFormat);

或者更好:

LocalTime localTime = LocalDateTime.parse(newAppointment.getStart(), format)
    .toLocalTime();

输出

11:00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    相关资源
    最近更新 更多