欢迎来到Java学习网!
设为首页 | 加入收藏
当前位置: 首页 > Java语言 > Java教程 >
private String dateToRelativeTime(Date date){
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     
    Date now=new Date();
    long between=(now.getTime()-date.getTime())/1000;//除以1000是为了转换成秒
    long day=between/(24*3600);
    long hour=between%(24*3600)/3600;
    long minute=between%3600/60;
    long second=between;
     
    String timeStr;
    if(day>0&&day<=29){
        timeStr=day+"天前";
    }else if(day>29){
        timeStr=df.format(date);
    }else{
        if(hour>0){
            timeStr=hour+"小时前";
        }else{
            if(minute>0){
                timeStr=minute+"分钟前";
            }else{
                timeStr=second+"秒前";
            }
        }
    }
    return timeStr;
}


    相关教程
    推荐内容