How to combine date and time into a single object?

后端 未结 3 1550
终归单人心
终归单人心 2020-12-01 23:36

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

相关标签:
3条回答
  • 2020-12-02 00:14

    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.

    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));
        }
    
    0 讨论(0)
  • 2020-12-02 00:16

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

    EDIT

    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);
    
    0 讨论(0)
  • 2020-12-02 00:23

    Simple yet effective would be:

    LocalDateTime dateTime = LocalDateTime.of(datePart, timePart);
    
    0 讨论(0)
提交回复
热议问题