Best way to format a date relative to now on Android

前端 未结 10 1711
隐瞒了意图╮
隐瞒了意图╮ 2021-01-31 15:57

I am creating a feature in an Android app to get an arbitrary date (past, present or future) and find the difference relative to now.

Both my now and

10条回答
  •  后悔当初
    2021-01-31 16:55

    Why not just check for yesterday and tomorrow to avoid the in 0 days/0 days ago bug and leave DateUtils.getRelativeTimeSpanString handle the remaining cases?

    String relative = null;
    
    if(now < due && (due-now)<864000){
        relative = "tomorrow";
    }else if(now > due && (now-due)<864000){
        relative = "yesterday";
    }else{
        relative = DateUtils.getRelativeTimeSpanString(due, now, DateUtils.DAY_IN_MILLIS); // e.g. "in 4 days"
    }
    
    Log.d("result", relative);
    

    Edit: You may also add today with a simple check as well.

提交回复
热议问题