How to combine date and time in one object?

my dao page gets date and time from two different fields. Now I want to know how to combine these dates and times in one object, so that I calculate the time difference and the total time. I have this code to merge, but it does not work, 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);
+6
source share
2 answers

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

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

EDIT

-, Date 2 . , , SimpleDateFormat. , .

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

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

Source: https://habr.com/ru/post/1016950/


All Articles