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

后端 未结 9 2136
鱼传尺愫
鱼传尺愫 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:14

    my understanding of the question is provide a simple method to produce output like the following:

    Today at 20:00
    Today at 20:30
    Today at 21:00
    Tomorrow at 06:45
    Tomorrow at 07:00
    Tomorrow at 08:15
    

    the code below worked for me, but i am new to android and maybe others could point out if the code is not robust. in code below 'timeLong' is the time of my events in epoch time (milliseconds).

    public String convertFromEpochTime (long timeLong) {
        long timeNow = System.currentTimeMillis();
    
        // get day in relative time
        CharSequence timeDayRelative;
        timeDayRelative = DateUtils.getRelativeTimeSpanString(timeLong, timeNow, DateUtils.DAY_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE);
    
        // get hour in 24 hour time
        Format hourFormatter = new SimpleDateFormat("HH:mm");
        String timeHour = hourFormatter.format(timeLong);
    
        // Log.d(DEBUG_TAG, "time of event: " + timeDayRelative + " at " + timeHour);
    
        String timeDayHour = timeDayRelative + " at "+ timeHour;
    
        return timeDayHour;
    }
    
    0 讨论(0)
  • 2020-12-30 06:15

    Look at jodatime: http://joda-time.sourceforge.net/

    this is some example code from the doc:

    public boolean isAfterPayDay(DateTime datetime) {
      if (datetime.getMonthOfYear() == 2) {   // February is month 2!!
        return datetime.getDayOfMonth() > 26;
      }
      return datetime.getDayOfMonth() > 28;
    }
    
    public Days daysToNewYear(LocalDate fromDate) {
      LocalDate newYear = fromDate.plusYears(1).withDayOfYear(1);
      return Days.daysBetween(fromDate, newYear);
    }
    
    public boolean isRentalOverdue(DateTime datetimeRented) {
      Period rentalPeriod = new Period().withDays(2).withHours(12);
      return datetimeRented.plus(rentalPeriod).isBeforeNow();
    }
    
    public String getBirthMonthText(LocalDate dateOfBirth) {
      return dateOfBirth.monthOfYear().getAsText(Locale.ENGLISH);
    }
    
    0 讨论(0)
  • 2020-12-30 06:18

    This is extended versino of Balusc's implementation.

    Try this, i implemented it using joda-datatime2.2.jar and SimpleDateFormat

    import java.text.SimpleDateFormat;
    import java.util.Date;
    import org.joda.time.DateMidnight;
    import org.joda.time.DateTime;
    import org.joda.time.Days;
    public class SmartDateTimeUtil {
    private static String getHourMinuteString(Date date){
        SimpleDateFormat hourMinuteFormat = new SimpleDateFormat(" h:m a");
        return hourMinuteFormat.format(date);
    }
    
    private static String getDateString(Date date){
        SimpleDateFormat dateStringFormat = new SimpleDateFormat("EEE',' MMM d y',' h:m a");
        return dateStringFormat.format(date);
    }
    
    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 boolean isTomorrow(DateTime dateTime){
        DateMidnight tomorrow = (new DateMidnight()).plusDays(1);
           return tomorrow.equals(dateTime.toDateMidnight());
    }
    private static String getDayString(Date date) {
            SimpleDateFormat weekdayFormat = new SimpleDateFormat("EEE',' h:m a");
            String s;
            if (isToday(new DateTime(date)))
                s = "Today";
            else if (isYesterday(new DateTime(date)))
                s = "Yesterday," + getHourMinuteString(date);
            else if(isTomorrow(new DateTime(date)))
                s = "Tomorrow," +getHourMinuteString(date);
            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 = "Today,"+getHourMinuteString(date);
            else if (days < 7)
                s = getDayString(date);
            else
                s = getDateString(date);
            return s;
    }
    
    }
    

    Simple cases to use and test the Util class:

    import java.util.Calendar;
    import java.util.Date;
    
    public class SmartDateTimeUtilTest {
        public static void main(String[] args) {
            System.out.println("Date now:"+SmartDateTimeUtil.getDateString_shortAndSmart(new Date()));
            System.out.println("Date 5 days before :"+SmartDateTimeUtil.getDateString_shortAndSmart(getFutureDay(-5)));
            System.out.println("Date 1 day before :"+SmartDateTimeUtil.getDateString_shortAndSmart(getFutureDay(-1)));
            System.out.println("Date last month:"+SmartDateTimeUtil.getDateString_shortAndSmart(getFutureMonth(-1)));
            System.out.println("Date last year:"+SmartDateTimeUtil.getDateString_shortAndSmart(getFutureDate(-1)));
            System.out.println("Date 1 day after :"+SmartDateTimeUtil.getDateString_shortAndSmart(getFutureDay(1)));
        }
        public static Date getFutureDate(int numberOfYears){
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.YEAR, numberOfYears); 
            return c.getTime();
        }
        public static Date getFutureMonth(int numberOfYears){
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.MONTH, numberOfYears); 
            return c.getTime();
        }
    
        public static Date getFutureDay(int numberOfYears){
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.DATE, numberOfYears); 
            return c.getTime();
        }
    }
    
    0 讨论(0)
  • 2020-12-30 06:21

    I know I am late to this party. But I have shortest solution for this problem. If you want to show "Today" or "Yesterday" based on the Date then you just need to use this

    String strDate = "";
    if (DateUtils.isToday(date.getTime()))
        strDate = "Today";
    else if (DateUtils.isToday(date.getTime() + DateUtils.DAY_IN_MILLIS))
        strDate = "Yesterday";
    

    here variable date is the Date object.

    0 讨论(0)
  • 2020-12-30 06:26

    Another way of comparing dates apart from the accepted answer above using java.util.Date.getTime() (note: long should be used instead of int):

    Date today=new Date();
    Date dateObj=null;
    long diff=0;
    try{
        dateObj= formater1.parse(date);
        diff=(today.getTime()-dateObj.getTime())/(86400000);
    }catch(Exception e){}
    String days="TODAY";
    if(diff==1){
        days = "YESTERDAY";
    }else if(diff>1){
        days = String.valueOf(diff) + " " +"DAYS AGO";
    }
    

    <%=days%> would return:

    TODAY

    YESTERDAY

    x DAYS AGO

    0 讨论(0)
  • 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. :)

    0 讨论(0)
提交回复
热议问题