-1

I am new to Java. I have a requirement to calculate the number of days, hour, time, sec from a given date to today, current time.

For example, I am getting 2 fields from database: Date and Time.
Date field is in the format Wednesday 02-October-2022 and Time field in the format 11:51:1 PM

In my Java class, I am able to pass these 2 field in String format:

public String getLastRun(String failedDate, String failedTime)
{

}

String failedDate, String failedTime are the Date and Time I got from DB in above format.

Now the issue is I need to calculate the number of days, hour, time, sec passed from that Date and time taken as input.

So, if current date is Thursday 02-November-2022 and time is 11:51:1 PM, I can calculate the number of days, hour, time, sec passed.
Example: Output: Last service failed 30 Days 12 hours 55 minutes 45 seconds Kind of output calculating the given Date and time field as input to this current Date and time?

So far, I have taken this Date and Time as input in this format of Wednesday 02-October-2022 and 11:51:1 PM in the Java class, but I am still not sure about:

  1. How to generate or fetch current Date and Time in this format in Java code?
  2. How to calculate the number of days, hour, time, sec passed from the given format with current Date and Time?

I have checked these following links: Link1, Link2 with local dates, but none of these have helped me to get the number of days, hour, time, sec from the given date and time format dynamically.
I even tried with SimpleDateFormat as mentioned here but not able to get with this format.

Any sample or pointer to start with will be helpful.
Pls Note: Time zone is IST Asia/Kolkata

  • 2
    Working here with IST time zone Asia/Kolkata – Shashank Raj Nov 02 '22 at 19:24
  • Those details belong in the Question, not the Comments. – Basil Bourque Nov 02 '22 at 19:25
  • 1
    edited the question.. added at the end – Shashank Raj Nov 02 '22 at 19:29
  • Assuming that date and time are stored as `date` and `time` in the database (as they should be), do not retrieve them as strings. Retrieve a `LocalDate` and a `LocalTime` object so you do not have to parse them. See for example [this question](https://stackoverflow.com/questions/43039614/insert-fetch-java-time-localdate-objects-to-from-an-sql-database-such-as-h2) and [this one](https://stackoverflow.com/questions/285553/dates-with-no-time-or-timezone-component-in-java-mysql). – Ole V.V. Nov 03 '22 at 06:12
  • 1
    Allow me to suggest you search a bit harder. This might be helpful, for example? [Difference Between Two Dates in Java](https://www.baeldung.com/java-date-difference). When you search, prefer the search results that use [java.time, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/index.html) as do the two answers posted so far. – Ole V.V. Nov 03 '22 at 06:21

2 Answers2

2

Parse your date as a LocalDate using DateTimeFormatter. This has been covered many times already on Stack Overflow.

Parse your time of day as a LocalTime using DateTimeFormatter. This has been covered many times already on Stack Overflow.

Specify your intended time zone.

ZoneId zone = ZoneId.of( "Asia/Kolkata" ) ;

Combine.

ZonedDateTime zdt = ZonedDateTime.of( date , time , zone ) ;

Adjust to UTC by extracting an Instant.

Instant then = zdt.toInstant () ;

Use Duration to calculate elapsed time on a scale of 24-hour long “days” (not calendar days), hours, minutes, seconds, and nanos.

Duration duration = Duration.between ( then , Instant.now() ) ;

The ideal solution would be educating the publisher of your data on using standard ISO 8601 formats.


Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • I am very new to this. Some more details or reference will be helpful. – Shashank Raj Nov 02 '22 at 19:40
  • @ShashankRaj Search Stack Overflow to learn more. Your Question is a duplicate of others. And study [tutorial](https://docs.oracle.com/javase/tutorial/datetime/TOC.html) by Oracle, free of cost. – Basil Bourque Nov 02 '22 at 19:43
  • I am trying to get the output from this format which I am not getting from any tutorial or even stackoverflow. That's the reason I asked to give some more details so that I can take it forward. I am trying to understand from your answer – Shashank Raj Nov 02 '22 at 19:50
  • For formatting the result use your search engine. Among many results I found [this](https://stackoverflow.com/questions/3471397/how-can-i-pretty-print-a-duration-in-java). And of course see the other answer. – Ole V.V. Nov 03 '22 at 10:33
1

Your steps should be as follows:

  1. Parse the date string into LocalDate using the applicable DateTimeFormatter.
  2. Parse the time string into LocalTime using the applicable DateTimeFormatter.
  3. Create an instance of LocalDateTime using the instances of LocalDate and LocalTime obtained from the above steps.
  4. Find the Duration between the obtained LocalDateTime and the current date-time.
  5. Get the days, hours, minutes, seconds from the obtained Duration.

Demo:

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
  public static void main(String[] args) {
    // Test
    System.out.println(getLastRun("Wednesday 05-October-2022", "11:51:1 PM"));
  }

  public static String getLastRun(String failedDate, String failedTime) {
    LocalDateTime givenDateTime = LocalDateTime.of(
        LocalDate.parse(failedDate, DateTimeFormatter.ofPattern("EEEE dd-MMMM-uuuu", Locale.ENGLISH)),
        LocalTime.parse(failedTime, DateTimeFormatter.ofPattern("h:m:s a", Locale.ENGLISH)));

    LocalDateTime now = LocalDateTime.now();

    Duration duration = givenDateTime.isAfter(now) ? Duration.between(now, givenDateTime)
        : Duration.between(givenDateTime, now);

    return String.format("Last service failed %d Days %d hours %d minutes %d seconds",
        duration.toDaysPart(), duration.toHoursPart(), duration.toMinutesPart(), duration.toSecondsPart());
  }
}

Output:

Last service failed 27 Days 21 hours 27 minutes 49 seconds

Learn more about the modern Date-Time API from Trail: Date Time and about the Duration through Q/As tagged with duration.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110