You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio Java中判断更新时间距当前是否超24小时并修改TableRow背景

解决方法

你只需要把原有时间对比的逻辑替换为时间差判断即可,24小时对应的毫秒值为86400000,计算当前时间和更新时间的毫秒差,判断差值是否大于等于该值即可实现需求。

修改后完整代码

JobRepository jobRepository = new JobRepository(a.getApplication());
jobRepository.findEnquiry().observe(getViewLifecycleOwner(), jobsEnquiry -> {
    TableRow[] tableRows = new TableRow[jobsEnquiry.size()];
    // 提前定义24小时对应的毫秒常量,避免重复计算
    final long ONE_DAY_MILLIS = 24 * 60 * 60 * 1000;

    for (int i=0; i<jobsEnquiry.size(); i++) {
        Job job = jobsEnquiry.get(i).job;
        tableRows[i] = new TableRow(a);
        tableRows[i].setId(i + 1);
        tableRows[i].setPadding(0,20,0,20);
        if(job.getStatus().equals("Left message/Awaiting reply")){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd H:m:s");
            Date updatedDate = job.getUpdatedAt();
            Date date = job.getDate();
            Date currentTime = Calendar.getInstance().getTime();
            tableRows[i].setBackgroundResource(android.R.drawable.list_selector_background);
            tableRows[i].setBackgroundResource(R.drawable.table_outline);

            // 核心修改:计算时间差是否满24小时
            long timeDiff = currentTime.getTime() - updatedDate.getTime();
            if (timeDiff >= ONE_DAY_MILLIS){
                tableRows[i].setBackgroundResource(android.R.drawable.list_selector_background);
                tableRows[i].setBackgroundResource(R.drawable.table_outline_status);
            }

        }
        else if(job.getStatus().equals("Action required")){
            tableRows[i].setBackgroundResource(android.R.drawable.list_selector_background);
            tableRows[i].setBackgroundResource(R.drawable.table_outline_status);
        }
        // 原有后续逻辑保持不变
    }
});

补充注意点

  • 如果你的项目minSdkVersion ≥ 26,更推荐使用java.time包的API做时间计算,可以避免时区、夏令时等异常场景的计算误差,示例逻辑如下:
Duration duration = Duration.between(updatedDate.toInstant(), Instant.now());
if (duration.toHours() >= 24) {
    // 满24小时的对应逻辑
}
  • 原有代码中连续两次调用setBackgroundResource会覆盖前一次的设置,如果你需要同时保留selector和边框效果,建议使用LayerDrawable实现,不需要重复调用set方法。

内容的提问来源于stack exchange,提问作者KCYrgn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 18:45:01