Calculating the time difference between two time stamp object - java

10,973

Solution 1

Manual time calculation:-

Converts Date in milliseconds (ms) and calculate the differences between two dates, with following rules :

  • 1000 milliseconds = 1 second
  • 60 seconds = 1 minute
  • 60 minutes = 1 hour
  • 24 hours = 1 day

Sample Example:-

package com.dps2.practice.dyuti;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDifferentExample {

    public static void main(String[] args) {

        String dateStart = "08/11/2016 09:29:58";
        String dateStop = "08/12/2016 10:31:48";

        //HH converts hour in 24 hours format (0-23), day calculation
        SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

        Date d1 = null;
        Date d2 = null;

        try {
            d1 = format.parse(dateStart);
            d2 = format.parse(dateStop);

            //in milliseconds
            long diff = d2.getTime() - d1.getTime();

            long diffSeconds = diff / 1000 % 60;
            long diffMinutes = diff / (60 * 1000) % 60;
            long diffHours = diff / (60 * 60 * 1000) % 24;
            long diffDays = diff / (24 * 60 * 60 * 1000);

            System.out.print(diffDays + " days, ");
            System.out.print(diffHours + " hours, ");
            System.out.print(diffMinutes + " minutes, ");
            System.out.print(diffSeconds + " seconds.");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Solution 2

The java.sql date-time classes are meant only for exchanging data with databases. Do not use them for business logic. Also, they are part of the troublesome, poorly designed, and confusing old legacy date-time classes. Avoid them all.

java.time

The java.time classes built into Java 8 and later supplant the old classes you are using. Much simpler now.

LocalDate ld = LocalDate.parse ( "2010-01-06" );
LocalTime lt = LocalTime.parse ( "01:00" );
LocalDateTime earlier = LocalDateTime.of ( ld , lt );

LocalDateTime later = earlier.plusHours ( 7 );

The Duration class represents a span of time as a total number of seconds and nanoseconds. Its toString method generates a String in the standard ISO 8601 format PnYnMnDTnHnMnS. This format uses P to mark the beginning, and the T to separate year-months-days from hours-minutes-seconds portion. The Duration and Period classes can both parse and generate such Strings.

Duration duration = Duration.between ( earlier , later );

In Java 8, Duration class inexplicably lacks getter methods for each part: days, hours, minutes, seconds, fraction-of-second. Java 9 rectifies this omission with new getPart methods.

Dump to console.

System.out.println ( "earlier: " + earlier + " | later: " + later + " | duration: " + duration );

earlier: 2010-01-06T01:00 | later: 2010-01-06T08:00 | duration: PT7H

Time zone

Be aware that your inputs lacked any information about offset-from-UTC or time zone. So the math seen above is performed assuming generic 24-hour days. Real-world anomalies such as Daylight Saving Time (DST) are ignored.

If you did indeed intend time zones, assign them via the atZone method to instantiate OffsetDateTime or ZonedDateTime objects.

Solution 3

The problem with your calculation is this: StartDate.getDay() etc.

getDay() will return the number of day of the week (read the JavaDoc) and not the day of the month. You'll need to use getDate() instead.

To illustrate the problem using your values: 2010-01-05 will return 2 for getDay() and thus you are getting 2010-01-02 as your timestamp. 2010-01-11 will return 1 for getDay() (it's 6 days later, i.e. (2 + 6) % 7 = 1) and hence your second timestamp becomes 2010-01-01. Now the second timestamp is before the first and hence you get a negative value.

However, as I already stated in my comments you should try and use some library or at least the non-deprecated built-in functionality for those calculations to save you a lot of headaches (I suggest you watch this video to get an idea of the challenges: https://youtube.com/watch?v=-5wpm-gesOY ).

Solution 4

That's a complicated code you have in your question there. You can make it quite easy by using java.util.concurrent.TimeUnit class.

Output

Date Tue Jan 05 00:00:00 UTC 2010                                                                                                                                                                                                                
Date Wed Jan 06 00:00:00 UTC 2010

difference is:                                                                                                                                                                                                                
24 hours : 1440 minutes : 86400 seconds 

Code

import java.util.*;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;

public class HelloWorld {

    public static void main(String[] args) {

        String date = "2010-01-05";
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date date3 = null;
        try {
            date3 = sdf1.parse(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Date StartDate = new Date(date3.getTime());
        System.out.println("Date " + StartDate);

        String date2 = "2010-01-06";
        java.util.Date date4 = null;
        try {
            date4 = sdf1.parse(date2);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        Date EndDate = new Date(date4.getTime());
        System.out.println("Date " + EndDate);



        long dateStart = StartDate.getTime(), dateStop = EndDate.getTime();
        long diff = dateStop - dateStart;

        long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(diff);
        long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(diff);
        long diffInHours = TimeUnit.MILLISECONDS.toHours(diff);

        System.out.println("\n\ndifference is:\n");
        System.out.println(diffInHours + " hours : " + diffInMinutes + " minutes : " + diffInSeconds + " seconds");
    }
}
Share:
10,973

Related videos on Youtube

Karthi Krazz
Author by

Karthi Krazz

Updated on May 25, 2022

Comments

  • Karthi Krazz
    Karthi Krazz almost 2 years

    I am having java.sql.date and java.sql.time objects, I need to find the time duration between the dates.

    So i am creating java.sql.timestamp object by using above date and time object

      Timestamp timestamp1 = new Timestamp(StartDate.getYear(),
            StartDate.getMonth(), StartDate.getDay(),
            StartTime.getHours(), StartTime.getMinutes(), 00,
            00);
    

    Here is mycode

    String date = "2010-01-05";
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date date3 = null;
        try {
            date3 = sdf1.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date StartDate = new Date(date3.getTime());
        System.out.println("Date " + StartDate);
    
        String date2 = "2010-01-06";
        java.util.Date date4 = null;
        try {
            date4 = sdf1.parse(date2);
        } catch (ParseException exception) {
            exception.printStackTrace();
        }
        Date EndDate = new Date(date4.getTime());
        System.out.println("Date " + EndDate);
    
        String time = "01:00";
        DateFormat formatter = new SimpleDateFormat("HH:mm");
        java.sql.Time StartTime = null;
        try {
            StartTime = new java.sql.Time(formatter.parse(time).getTime());
        } catch (ParseException exception2) {
            exception2.printStackTrace();
        }
        System.out.println("TIMEEEEEEEEEE====" + StartTime);
    
        String time2 = "02:00";
        java.sql.Time EndTime = null;
        try {
            EndTime = new java.sql.Time(formatter.parse(time2).getTime());
        } catch (ParseException exception3) {
            exception3.printStackTrace();
        }
        System.out.println("TIMEEEEEEEEEE====" + EndTime);
    
    
        Timestamp timestamp1 = new Timestamp(StartDate.getYear(),
                StartDate.getMonth(), StartDate.getDay(),
                StartTime.getHours(), StartTime.getMinutes(), 00,
                00);
        Timestamp timestamp2 = new Timestamp(EndDate.getYear(),
                EndDate.getMonth(), EndDate.getDay(),
                EndTime.getHours(), EndTime.getMinutes(), 00, 00);
    
        long milliseconds = timestamp2.getTime() - timestamp1.getTime();
        int seconds = (int) milliseconds / 1000;
    
        // calculate hours minutes and seconds
        int hours = seconds / 3600;
        int minutes = (seconds % 3600) / 60;
        seconds = (seconds % 3600) % 60;
        System.out.println(hours+"h:"+minutes+"m:"+"00s");
    

    Test case

    when I give date as 2010-01-05 and date2 as 2010-01-06 I am getting output as below

    Date 2010-01-05
    Date 2010-01-06
    TIMEEEEEEEEEE====01:00:00
    TIMEEEEEEEEEE====02:00:00
    25h:0m:00s
    

    when I give date as 2010-01-05 and date2 as 2010-01-11 I am getting output in negative value as below

    Date 2010-01-05
    Date 2010-01-11
    TIMEEEEEEEEEE====01:00:00
    TIMEEEEEEEEEE====02:00:00
    -23h:0m:00s
    

    Help me to correct if I am doing something wrong. Thanks in advance.

    • Thomas
      Thomas almost 8 years
      Did you debug your code? Are the dates/timestamps correct or already corrupted? Btw, you should use Calendar to build dates instead of the deprecated constructors. Also note that timezones and daylight saving time as well as other influences (leap seconds for example) can influence your manual calculations, i.e. the number of seconds between two dates might not be what you'd expect. Thus I'd suggest using one of the available libraries (e.g. Joda Time or if you're using Java 8 the new built-in date library).
    • Thomas
      Thomas almost 8 years
    • SaviNuclear
      SaviNuclear almost 8 years
      You are converting your date in time format so that you are getting like that.
  • Basil Bourque
    Basil Bourque almost 8 years
    Doing this math yourself is silly given that we have the java.time classes at our disposal.