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

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

提交回复
热议问题