Simplify replacement of date object with “today” and “yesterday” strings in Java static method

后端 未结 9 2213
鱼传尺愫
鱼传尺愫 2020-12-30 05:55

I have following method that I would like to make shorter or faster if nothing else. Please all comments are welcome:

Bellow method takes a date object, formates i

9条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 06:27

    You wrote "all comments welcome" so here's my way using joda-time. :)

    I am a fan of displaying dates and times in the short and smart way of iPhone's recent calls (similar to google wave posts). That is "hh:mm" if today, "yesterday" or name of weekday if <7 days, else yyyy-MM-dd.

    private static boolean isToday (DateTime dateTime) {
       DateMidnight today = new DateMidnight();
       return today.equals(dateTime.toDateMidnight());
    }
    
    private static boolean isYesterday (DateTime dateTime) {
       DateMidnight yesterday = (new DateMidnight()).minusDays(1);
       return yesterday.equals(dateTime.toDateMidnight());
    }
    
    private static String getDayString(Date date) {
        String s;
    
        if (isToday(new DateTime(date)))
            s = "Today";
        else if (isYesterday(new DateTime(date)))
            s = "Yesterday";
        else
            s = weekdayFormat.format(date);
    
        return s;
    }
    
    public static String getDateString_shortAndSmart(Date date) {
        String s;
    
        DateTime nowDT = new DateTime();
        DateTime dateDT = new DateTime(date);
        int days = Days.daysBetween(dateDT, nowDT).getDays();
    
        if (isToday(new DateTime(date)))
            s = getHourMinuteString(date);
        else if (days < 7)
            s = getDayString(date);
        else
            s = getDateString(date);
    
        return s;
    }
    

    where I use a set of SimpleDateFormat (as weekdayFormat above) to format the time to the desired strings, and where DateTime and DateMidnight are joda-time classes.

    In these cases the number of elapsed days between two DateTime:s is less relevant than how people would define the time talking about it. Instead of counting days (or milliseconds as I've seen some people do) DateMidnight comes handy here, though other methods would work just as well. :)

提交回复
热议问题