Right way to format date with strings like today, yesterday, tomorrow etc

前端 未结 6 575
臣服心动
臣服心动 2021-02-04 00:31

I have a date textview. And my textview holds a date string like 2011.09.17. Well I still do want to have that but I also want to add some more user friendly info for some speci

6条回答
  •  故里飘歌
    2021-02-04 01:02

    For android Use JodaTime library in build.gradle file:

    compile 'net.danlew:android.joda:2.9.9'

    public static String formateddate(String date) {
        DateTime dateTime = DateTimeFormat.forPattern("dd-MMM-yyyy").parseDateTime(date);
        DateTime today = new DateTime();
        DateTime yesterday = today.minusDays(1);
        DateTime twodaysago = today.minusDays(2);
        DateTime tomorrow= today.minusDays(-1);
    
        if (dateTime.toLocalDate().equals(today.toLocalDate())) {
            return "Today ";
        } else if (dateTime.toLocalDate().equals(yesterday.toLocalDate())) {
            return "Yesterday ";
        } else if (dateTime.toLocalDate().equals(twodaysago.toLocalDate())) {
            return "2 days ago ";
        } else if (dateTime.toLocalDate().equals(tomorrow.toLocalDate())) {
            return "Tomorrow ";
        } else {
            return date;
        }
    }
    

提交回复
热议问题