Java实现JSON时间戳转相对时间并在RecyclerView展示
解决方案
1. 编写时间转换工具类
先创建一个工具类,用来把秒级时间戳转换成相对时间格式:
public class TimeUtils { public static String getRelativeTime(long timestamp) { // 将秒级时间戳转为毫秒级 long publishedTime = timestamp * 1000; long currentTime = System.currentTimeMillis(); long diff = currentTime - publishedTime; // 计算时间差对应的单位 long seconds = diff / 1000; long minutes = seconds / 60; long hours = minutes / 60; long days = hours / 24; long weeks = days / 7; long months = days / 30; long years = days / 365; if (seconds < 60) { return seconds + "秒前"; } else if (minutes < 60) { return minutes + "分钟前"; } else if (hours < 24) { return hours + "小时前"; } else if (days < 7) { return days + "天前"; } else if (weeks < 4) { return weeks + "周前"; } else if (months < 12) { return months + "个月前"; } else { return years + "年前"; } } }
2. 确保实体类能获取时间戳
确认你的数据实体类(比如NewsItem)包含published_on字段的getter方法:
public class NewsItem { // 其他字段及getter方法 private long published_on; public long getPublishedOn() { return published_on; } }
3. 修改RecyclerView的ViewHolder与绑定逻辑
首先在ViewHolder中添加显示时间的TextView:
public class MyViewHolder extends RecyclerView.ViewHolder { TextView title, body, tvRelativeTime; ImageView imageViewUrl; public MyViewHolder(@NonNull View itemView) { super(itemView); title = itemView.findViewById(R.id.tv_title); body = itemView.findViewById(R.id.tv_body); tvRelativeTime = itemView.findViewById(R.id.tv_relative_time); imageViewUrl = itemView.findViewById(R.id.iv_image); } }
然后修改onBindViewHolder方法,添加相对时间的设置逻辑:
@Override public void onBindViewHolder(@NonNull MyViewHolder holder, int position) { NewsItem currentItem = dataList.get(position); holder.title.setText(currentItem.getTitle()); holder.body.setText(currentItem.getBody()); // 生成并设置相对时间 String relativeTime = TimeUtils.getRelativeTime(currentItem.getPublishedOn()); holder.tvRelativeTime.setText(relativeTime); Glide.with(mContext) .load(currentItem.getImageurl()) .into(holder.imageViewUrl); }
这样就能将JSON中的秒级时间戳转换为「3分钟前」「1天前」这类相对时间格式,并在RecyclerView的每个条目里展示出来。
内容的提问来源于stack exchange,提问作者Reny
相关产品推荐
相关产品推荐

