如何将日期和时间组合成单个对象? [英] 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);
推荐答案
你只需要使用正确的方法,而不是调用构造函数。使用解析
创建本地日期和本地时间对象,然后将这两个对象传递给<$ c的
方法$ c> LocalDateTime :
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屋!