如何将日期和时间组合成一个对象?

2022-09-02 23:42:35

我的道页面正在从两个不同的字段接收日期和时间,现在我想知道如何将这些日期和时间合并到一个对象中,以便我计算时差和总时间。我有这个代码要合并,但它不起作用,我在这个代码中做错了什么,请帮助。

    Date d = new SimpleDateFormat("yyyy-MM-dd").parse("2013-01-02");
    Date t = new SimpleDateFormat("hh:mm:ss").parse("04:05:06");
    LocalDate datePart = new LocalDate(d);
    LocalTime timePart = new LocalTime(t);
    LocalDateTime dateTime = datePart.toLocalDateTime(timePart);
    System.out.println(dateTime);

答案 1

您只需要使用正确的方法,而不是调用构造函数。用于创建本地日期和本地时间对象,然后将这两个对象传递给以下方法:parseofLocalDateTime

    LocalDate datePart = LocalDate.parse("2013-01-02");
    LocalTime timePart = LocalTime.parse("04:05:06");
    LocalDateTime dt = LocalDateTime.of(datePart, timePart);

编辑

显然,您需要组合两个对象而不是2个字符串。我想您可以先使用将两个日期转换为字符串。然后使用上面显示的方法。DateSimpleDateFormat

String startingDate = new SimpleDateFormat("yyyy-MM-dd").format(startDate);
String startingTime = new SimpleDateFormat("hh:mm:ss").format(startTime);

答案 2

要在java 8中组合日期和时间,您可以使用。这还允许您使用 的格式。java.time.LocalDateTimejava.time.format.DateTimeFormatter

示例程序:

public static void main(String[] args) {
        LocalDate date = LocalDate.of(2013, 1, 2);
        LocalTime time = LocalTime.of(4, 5, 6);
        LocalDateTime localDateTime = LocalDateTime.of(date, time);
        DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy  hh:mm a");
        System.out.println(localDateTime.format(format));
    }