-2

I have DateTime string 2020-04-03 01:29:27 and 2020-04-03 01:29:37 I want to get duration in hours. I have tried many things but this but cant find any help

str
  • 38,402
  • 15
  • 99
  • 123
anduplats
  • 705
  • 2
  • 9
  • 20

2 Answers2

5

I have tried many things but this but cant find any help

Do these "many things" include consulting the javadoc where you would find that:

// assuming both dates are in d1 and d2

Duration duration = Duration.between(d1, d2);

long hours = duration.toHours(); 

Hope that helps.

hd1
  • 32,598
  • 5
  • 75
  • 87
0

java.time

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dt1 = LocalDateTime.parse("2020-04-03 01:29:27", formatter);
        LocalDateTime dt2 = LocalDateTime.parse("2020-04-03 01:29:37", formatter);
        System.out.printf("%.4f Hour(s)", Duration.between(dt1, dt2).toSeconds() / 3600.0);
    }
}

Output:

0.0028 Hour(s)

Learn more about java.time API from Trail: Date Time.

Arvind Kumar Avinash
  • 62,771
  • 5
  • 54
  • 92