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

dee*_*wat 11 java datetime java-8

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

    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);
Run Code Online (Sandbox Code Playgroud)

Swe*_*per 19

您只需要使用正确的方法,而不是调用构造函数.使用parse创建本地日期和本地时间对象,那么这两个对象传递给of方法LocalDateTime:

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

编辑

显然,您需要组合两个Date对象而不是两个字符串.我想你可以先用两个日期转换成字符串SimpleDateFormat.然后使用上面显示的方法.

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

  • 完美展示了新的 DateTime API 的简单性。我可能会建议指出为什么上面的方法有效 - 即“t”实际上是一个日期,并且在 Java 8 之前不支持“时间”。 (2认同)
  • 需要注意的是,这需要 api 26 及更高版本 (2认同)

Jay*_*ith 5

要在 Java 8 中组合日期和时间,您可以使用java.time.LocalDateTime. 这也允许您使用java.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));
    }
Run Code Online (Sandbox Code Playgroud)