-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

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

And others whinge about it, eh?
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.