java - 如何使用 DateTimeFormatter 只获取时间?

标签 java date java-8 java-time

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

相关文章:

java - 编译 Java 8 中的一个奇怪的 NullPointerException(编译器(1.8.0_31))

java - 在封闭范围内定义的局部变量日志必须是最终的或实际上是最终的

java - Hadoop MapReduce 不处理/输出错误?

java - 为什么在重写 finalize 方法时引用不放入引用队列

java - 数据库中的数据未显示

r - lubridate::floor_date(x, "14 days"):如何防止新月份重新启动?

java - Grails 错误 - 执行 Bootstrap 时出错 : java. lang.ClassNotFoundException: DefaultQuartzConfig

java - 在 ArrayList 中按日期对 ArrayList 列表进行排序

javascript - 使日期对象考虑时区

java - 将数组/字符串列表转换为数组/整数列表的 Lambda 表达式