如何优化用于用户友好通知的时间差计算Java函数?
Java剩余时间计算函数优化建议请求
我编写了一个Java函数getRemainingTime(Date currentDate, Date expirationDate),用于计算两个日期的差值并返回用户友好格式的结果,主要用于向用户发送某事件剩余时间的通知,通知需每12小时发送一次。例如初始通知内容为**"You have left 6 days and 12 hours",12小时后再次发送时内容为"You have left 6 days"**,过期日期为应用内某事件发生后的7天。
函数代码如下:
public static String getRemainingTime(Date currentDate, Date expirationDate) { // Calculate the time difference in milliseconds between the two dates long diff = expirationDate.getTime() - currentDate.getTime(); long days = TimeUnit.MILLISECONDS.toDays(diff); long remainingMillisAfterDays = diff - TimeUnit.DAYS.toMillis(days); long hours = TimeUnit.MILLISECONDS.toHours(remainingMillisAfterDays); long remainingMillisAfterHours = remainingMillisAfterDays - TimeUnit.HOURS.toMillis(hours); long minutes = TimeUnit.MILLISECONDS.toMinutes(remainingMillisAfterHours); // Check and apply rounding if the time is close to the next day or hour if (hours == 23 && minutes >= 30) { days++; hours = 0; minutes = 0; } // Return the remaining time based on the calculated days, hours, and minutes if (days > 0 && (hours >= 12 || (hours == 11 && minutes >= 30))) { return days + " days and 12 hours"; } else if (days > 0) { return days + " days"; } else if (hours >= 11 || (hours == 10 && minutes >= 30)) { return "12 hours"; } else { return "less than one hour"; } }
该函数会对数值进行近似处理以提升用户理解度,例如将11小时30分钟近似为12小时,23小时30分钟近似为1天。
我的需求如下:
- 通知需以天和小时为单位显示剩余时间;
- 接近整值的时间(如11小时30分钟)需进行近似处理以优化用户体验;
- 计划根据函数返回值触发通知,例如当函数返回“12 hours”时,向用户发送内容为“12 hours have passed.”的通知。
恳请各位提供改进建议,谢谢!
内容的提问来源于stack exchange,提问作者JustinRyu2
相关产品推荐
相关产品推荐

