如何将日期和时间组合成一个对象? [英] How to combine date and time into a single object?
问题描述
我的 dao 页面正在接收来自两个不同领域的日期和时间,现在我想知道如何将这些日期和时间合并到一个对象中,以便我计算时差和总时间.我有这段代码要合并,但它不起作用我在这段代码中做错了什么,请帮忙.
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.
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);
推荐答案
你只需要使用正确的方法,而不是调用构造函数.使用parse
创建本地日期和本地时间对象,然后将这两个对象传递给LocalDateTime
的of
方法:
You just need to use the correct methods, instead of calling constructors. Use parse
to create local date and local time objects, then pass the two objects to the of
method of LocalDateTime
:
LocalDate datePart = LocalDate.parse("2013-01-02");
LocalTime timePart = LocalTime.parse("04:05:06");
LocalDateTime dt = LocalDateTime.of(datePart, timePart);
编辑
显然,您需要组合两个 Date
对象而不是 2 个字符串.我想您可以先使用 SimpleDateFormat
将两个日期转换为字符串.然后使用上面显示的方法.
Apparently, you need to combine two Date
objects instead of 2 strings. I guess you can first convert the two dates to strings using SimpleDateFormat
. Then use the methods shown above.
String startingDate = new SimpleDateFormat("yyyy-MM-dd").format(startDate);
String startingTime = new SimpleDateFormat("hh:mm:ss").format(startTime);
这篇关于如何将日期和时间组合成一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!