MahmoudBavarii
MahmoudBavarii

Reputation: 61

How to calculate the difference in minutes between two timeStamp ( with different days)?

I'm trying to calculate a difference in minutes between two java TimeStamps when I write: Timestamp t1,t2;

t2.getTime()-t1.getTime(); it returns only the difference between the two times and I need the difference the whole times (including days)

Upvotes: 0

Views: 1233

Answers (4)

Swapnil Patil
Swapnil Patil

Reputation: 613

    Timestamp t1 = new Timestamp(new Date("04/26/2019 20:32:49").getTime());
    Timestamp t2 = new Timestamp(new Date("04/27/2019 19:32:49").getTime());

    long diff = t2.getTime() - t1.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);
    long diffTotMinutes = diff / (60 * 1000);

    System.out.println("Days: " + diffDays + " \nTime: " + diffHours + ":" + diffMinutes + ":" + diffSeconds);
    System.out.println("Total Minutes: " + diffTotMinutes);

Out Put:

Days: 0 
Time: 23:0:0
Total Minutes: 1380

Upvotes: 0

Marwik
Marwik

Reputation: 1

Assuming you mean java.sql.Timestamp, the code below seems to work just fine:

import java.sql.Timestamp;

class Scratch {

    public static final long MINUTES_PER_HOUR = 60;
    public static final long SECONDS_PER_MINUTE = 60;
    public static final long HOURS_PER_DAY = 24;
    public static final long MILLIS_PER_SECOND = 1000L;

    public static void main(String[] args) {
        long oneDayPlusFiveMinutesInMillis = (MILLIS_PER_SECOND * SECONDS_PER_MINUTE) * ( 5 + MINUTES_PER_HOUR * HOURS_PER_DAY);
        Timestamp t0 = new Timestamp(System.currentTimeMillis());
        Timestamp t1 = new Timestamp(t0.getTime() + oneDayPlusFiveMinutesInMillis);
        long diff = (t1.getTime() - t0.getTime()) / (MILLIS_PER_SECOND * SECONDS_PER_MINUTE);
        System.out.println("t1 - t0 = " + diff + " minutes");
    }
}

Returns:

t1 - t0 = 1445 minutes

Upvotes: 0

abj1305
abj1305

Reputation: 665

Difference between 2 timestamps gives milliseconds. Apply Maths afterwards:

// get time difference in seconds
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;

Upvotes: 0

Jimale Abdi
Jimale Abdi

Reputation: 2854

Try this

long difftime = t1.getTime() - t2.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;

Upvotes: 1

Related Questions