如何使用 DateTimeFormatter 只获取时间?

How to use DateTimeFormatter to get time only?

我正在制作一个约会应用程序,并试图仅将约会时间填写到组合框中。到目前为止,我只能获得日期,但现在我无法获得时间。它在组合框中显示为 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));

是的,您需要将 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