場景
有這麼個業務需求,要統計用戶每天使用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分鐘