user3763216
user3763216

Reputation: 489

Calculate time difference from two unix time stamps and convert to minutes in Java

I have two UNIX time stamps, I want to compare them and then get the difference in minutes.

E.g. 1418600222 and 1418602180, where 1418602180 - 1418600222 gives me an answer in minutes. I tried to google it but most of the results are in javascript which i have a rather limited understanding of.

Upvotes: 2

Views: 4407

Answers (4)

Unix timestamp (also known as epoch time) is just the number of seconds since 00:00:00 of 1970-01-01.

Given that it is a number, you can compute the difference as with any other number. You will get the difference in seconds. Divide this by 60 to get difference in minutes.

Your example:

1418602180 is 2014-12-15 00:09:40 GMT
1418600222 is 2014-12-14 23:37:02 GMT

difference is 1418602180 - 1418600222 = 1958 seconds
1958 / 60 = 32.6333 minutes

Upvotes: 1

Natalia
Natalia

Reputation: 4532

look at java.util.concurrent.TimeUnit

java.util.concurrent.TimeUnit#SECONDS.toMinutes()

Upvotes: 1

SpringLearner
SpringLearner

Reputation: 13844

try this

public class tets {
public static void main(String args[])
{
    long timeStamp= 1418602180 - 1418600222;
    java.util.Date time=new java.util.Date(timeStamp*1000);
    System.out.println(time.getMinutes());
}
}

OUTPUT 2

UPDATE

In my previous example,I had used the deprecated methods. You can use joda time as below

LocalDateTime d1=new LocalDateTime(new Date(1418602180 *1000));
    LocalDateTime d2=new LocalDateTime(new Date(1418600222*1000));

    System.out.println(d1);
    System.out.println(d2);
    int minutesDiff=Minutes.minutesBetween(d2, d1).getMinutes();
    System.out.println(minutesDiff);

Upvotes: 1

mystery
mystery

Reputation: 935

        long t1=1418602180;
        long t2=1418600222;
        long minutes=Math.abs(t1-t2)/60;
        System.out.println(minutes);

Upvotes: 3

Related Questions