suhail c
suhail c

Reputation: 3

difference between 2 date objects in minutes in java

I want to get the difference between two date objects in java in minutes to find out how many minutes a user logined in my application.

    String query = "Select * from cabin_info where ip_address = ?";
        ps = con.prepareStatement(query);
        ps.setString(1, IPAddress);
        rs = ps.executeQuery();
        if (rs.next()) {
            cabin_id = rs.getInt("cabin_id");
            start_time = rs.getString("start_time");
            username = rs.getString("username");
        }
        Date st_time = AppConstants.time_format.parse(start_time);

        Date date = AppConstants.time_format.parse(AppConstants.time_format.format(new Date()));
        long diff = date.getTime() - st_time.getTime();
        long diffMinutes = diff / (60 * 1000) % 60;
        System.out.println("Total time = " + diffMinutes);

the datefromat is HH-mm-ss

But i get only the difference between the minutes in time not the time

Upvotes: 0

Views: 81

Answers (3)

Xavier ROBERT
Xavier ROBERT

Reputation: 11

long minutes = TimeUnit.MINUTES.convert(date.getTime() - st_time.getTime(), TimeUnit.MILLISECONDS)

Upvotes: 1

DeiAndrei
DeiAndrei

Reputation: 947

Since you are looking for the time interval in minutes, you only have to convert milliseconds to minutes.

minutes = milliseconds/(60*1000)

Therefore, your code:

 long diffMinutes = diff / (60 * 1000) % 60;

becomes:

 long diffMinutes = diff / (60 * 1000);

Adding a modulo 60 at the end would make sens if you want to compute hours and minutes.

Upvotes: 0

eLemEnt
eLemEnt

Reputation: 1801

long result = ((date.getTime()/60000) - (st_time.getTime()/60000));
System.out.println("Total time = " + result);

convert milliseconds to minute and just subtract it

Upvotes: 0

Related Questions