简体   繁体   English

Java中以分钟为单位的两个日期对象之间的差异

[英]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. 我想以分钟为单位获取java中两个日期对象之间的差异,以找出用户在我的应用程序中登录了多少分钟。

    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 datefromat是HH-mm-ss

But i get only the difference between the minutes in time not the time 但是我只得到分钟之间的差异而不是时间

长分钟= TimeUnit.MINUTES.convert(date.getTime()-st_time.getTime(),TimeUnit.MILLISECONDS)

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. 如果要计算小时和分钟数,则在末尾加上模60会很有意义。

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

convert milliseconds to minute and just subtract it 将毫秒转换为分钟,然后减去

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM