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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43752557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:41:44  来源:igfitidea点击:

How to combine date and time into a single object?

javadatetimejava-8

提问by deepak rawat

my dao page is receiving date and time from two different field now i want know how to merge these both date and time in a single object so that i calculate time difference and total time. I have this code to merge but it is not working what am i doing wrong in this code please help.

我的 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);

回答by Sweeper

You just need to use the correct methods, instead of calling constructors. Use parseto create local date and local time objects, then pass the two objects to the ofmethod of LocalDateTime:

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

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

EDIT

编辑

Apparently, you need to combine two Dateobjects instead of 2 strings. I guess you can first convert the two dates to strings using SimpleDateFormat. Then use the methods shown above.

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

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

回答by Jay Smith

To combine date and time in java 8 you can use java.time.LocalDateTime. This also allows you to format with java.time.format.DateTimeFormatter.

要在 Java 8 中组合日期和时间,您可以使用java.time.LocalDateTime. 这也允许您使用java.time.format.DateTimeFormatter.

Example program:

示例程序:

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));
    }

回答by Eric Smith

Simple yet effective would be:

简单而有效的是:

LocalDateTime dateTime = LocalDateTime.of(datePart, timePart);