-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
  • 42,689
  • 17
  • 109
  • 127
anduplats
  • 885
  • 2
  • 14
  • 24

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
  • 33,938
  • 5
  • 80
  • 91
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
  • 71,965
  • 6
  • 74
  • 110
  • 2
    And others whinge about it, eh? – hd1 Apr 03 '20 at 16:45
  • @hd1 - I didn't understand your comment. I tried to understand your comment by going through your answer but I couldn't make anything out of your comment. If your comment is about why I have used `.toSeconds() / 3600.0`, the answer is: purposefully. Had I used `Duration.between(dt1, dt2).toHours()`, it would have returned `0`. – Arvind Kumar Avinash Dec 05 '22 at 20:57