我正在制作一个约会应用程序,并试图仅将约会时间填写到组合框中。到目前为止,我只能获取日期,但现在我无法获取时间。它在组合框中显示为 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
关于java - 如何使用 DateTimeFormatter 只获取时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63009222/