随笔 统计用户每天使用时长

场景

有这么个业务需求,要统计用户每天使用app的时长(后台运行也算)。
经过讨论决定把打开app、并且为登陆状态的时间作为开始时间;把关闭、崩溃、强杀进程或者登出的时间作为结束时间,由客户端统计,发送给服务端进行计算。
计算时间差的方式有很多,但找了半天没有合适这个场景的,于是就自己写了一下,如有其他方式欢迎留言。

code

public class Application {
    private static final SimpleDateFormat simpleDateFormatLong = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat simpleDateFormatShort = new SimpleDateFormat("yyyy-MM-dd");

    public static void main(String[] args) throws ParseException {
        String fromStr = "2019-12-29 12:34:56";
        String toStr = "2020-01-02 12:00:00";
        System.out.println("开始时间:"+fromStr);
        System.out.println("结束时间:"+toStr);
        Date from = simpleDateFormatLong.parse(fromStr);
        Date to = simpleDateFormatLong.parse(toStr);
        if (from.compareTo(to) > 0) {
            System.out.println("param error");
        }
        Map<String, Integer> result = calculateMinute(from, to);
        for (Map.Entry<String, Integer> entry : result.entrySet()) {
            System.out.println("日期:" + entry.getKey() + "     使用时长:" + entry.getValue() + "分钟");
        }
    }

    private static Map<String, Integer> calculateMinute(Date from, Date to) {
        Map<String, Integer> result = new LinkedHashMap<>();

        Calendar comparisonValue = new GregorianCalendar();
        comparisonValue.setTime(from);
        comparisonValue.add(Calendar.DATE, 1);
        comparisonValue.set(Calendar.HOUR_OF_DAY, 0);
        comparisonValue.set(Calendar.MINUTE, 0);
        comparisonValue.set(Calendar.SECOND, 0);
        comparisonValue.set(Calendar.MILLISECOND, 0);

        while (to.compareTo(comparisonValue.getTime()) > 0) {
            long nextDayTime = comparisonValue.getTime().getTime();
            long fromTime = from.getTime();
            int nextDayMinutes = (int) ((nextDayTime - fromTime) / (1000 * 60));
            result.put(simpleDateFormatShort.format(from), nextDayMinutes);
            from = comparisonValue.getTime();
            comparisonValue.add(Calendar.DATE, 1);
        }
        long fromNew = from.getTime();
        long toNew = to.getTime();
        int minutesNew = (int) ((toNew - fromNew) / (1000 * 60));
        result.put(simpleDateFormatShort.format(from), minutesNew);
        return result;
    }
}

测试结果

开始时间:2019-12-29 12:34:56
结束时间:2020-01-02 12:00:00
日期:2019-12-29 使用时长:685分钟
日期:2019-12-30 使用时长:1440分钟
日期:2019-12-31 使用时长:1440分钟
日期:2020-01-01 使用时长:1440分钟
日期:2020-01-02 使用时长:720分钟

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值