if语句出现问题,除了几秒钟后什么也没有找回,我几秒钟后应该几分钟又几天

时间:2020-04-18 00:54:55

标签: java android

我需要以下逻辑的帮助,我似乎无法获得正确的结果。我需要合乎逻辑的播放-秒,然后过去59秒以使其回读分钟,然后过去59分钟以使其回读小时,然后是小时,应该说一天前和过去一天的过去24小时它应该在几天前读回。

就像我说的,事物的逻辑流动。 soemeone可以告诉我为什么我的if语句除了秒以外不返回任何内容吗?达到59秒后,它会以秒为单位闪烁,不会转换为分钟。

我想念什么?

//SECOND WAY

        //Current timestamp
        Calendar calendar = Calendar.getInstance();
        long ts = calendar.getTimeInMillis();

        //Getting comment timestamp from database
        long timestampOfComment = comment.getTimestamp();

        long duration = ts - timestampOfComment;

        long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
        long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
        long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
        long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);

        Log.d("SECONDS", diffInSeconds + " seconds ago");
        Log.d("MINUTES", diffInMinutes + " minutes ago");
        Log.d("HOURS", diffInHours + " hours ago");
        Log.d("DAYS", diffInDays + " days ago");

        if (diffInSeconds == 0) {
            holder.timestamp.setText("Just now");
        } else if (diffInSeconds != 0 && diffInSeconds < 59) {
            holder.timestamp.setText(diffInSeconds + " seconds ago");
        } else if (diffInSeconds != 0 && diffInSeconds > 59) {
            holder.timestamp.setText(diffInMinutes + " minutes ago");
        } else if (diffInSeconds != 0 && diffInSeconds > 59 && diffInMinutes > 59 && diffInHours == 1) {
            holder.timestamp.setText(diffInHours + " hour ago");
        } else if (diffInSeconds != 0 && diffInSeconds > 59 && diffInMinutes > 59 && diffInHours != 1 && diffInHours > 1) {
            holder.timestamp.setText(diffInHours + " hours ago");
        } else if (diffInSeconds != 0 && diffInSeconds > 59 && diffInMinutes > 59 && diffInHours != 1 && diffInHours > 1 && diffInDays == 1) {
            holder.timestamp.setText(diffInDays + " day ago");
        } else if (diffInSeconds != 0 && diffInSeconds > 59 && diffInMinutes > 59 && diffInHours != 1 && diffInHours > 1 && diffInDays != 1 && diffInDays > 1) {
            holder.timestamp.setText(diffInHours + " days ago");
        }

2 个答案:

答案 0 :(得分:1)

diffSeconds永远不会大于60,因为您使用的是%60。因此它将从58,59,0,1 ...依次类推

答案 1 :(得分:1)

您的答案JBM:

if(diffInDays > 0){ 
holder.timestamp.setText(diffInDays + " days ago"); 
}else if(diffInHours > 0){ 
holder.timestamp.setText(diffInHours + " hours ago"); 
}else if(diffInMinutes > 0){ 
holder.timestamp.setText(diffInMinutes + " minutes ago"); 
}else if(diffInSeconds > 0){ 
holder.timestamp.setText(diffInSeconds + " seconds ago"); 
}else { 
holder.timestamp.setText("Just now"); 
}