输出类似于 刚刚, 4分钟前, 一小时前, 昨天这样的时间

https://zhidao.baidu.com/question/560443336128190484.html 

/**
      * 格式化时间(输出类似于 刚刚, 4分钟前, 一小时前, 昨天这样的时间)
      *
      * @param time    需要格式化的时间 如"2014-07-14 19:01:45"
      * @param pattern 输入参数time的时间格式 如:"yyyy-MM-dd HH:mm:ss"
      *                <p/>如果为空则默认使用"yyyy-MM-dd HH:mm:ss"格式
      * @return time为null,或者时间格式不匹配,输出空字符""
      */
     public  static  String formatDisplayTime(String time, String pattern) {
         String display =  "" ;
         int  tMin =  60  1000 ;
         int  tHour =  60  * tMin;
         int  tDay =  24  * tHour;
 
         if  (time !=  null ) {
             try  {
                 Date tDate =  new  SimpleDateFormat(pattern).parse(time);
                 Date today =  new  Date();
                 SimpleDateFormat thisYearDf =  new  SimpleDateFormat( "yyyy" );
                 SimpleDateFormat todayDf =  new  SimpleDateFormat( "yyyy-MM-dd" );
                 Date thisYear =  new  Date(thisYearDf.parse(thisYearDf.format(today)).getTime());
                 Date yesterday =  new  Date(todayDf.parse(todayDf.format(today)).getTime());
                 Date beforeYes =  new  Date(yesterday.getTime() - tDay);
                 if  (tDate !=  null ) {
                     SimpleDateFormat halfDf =  new  SimpleDateFormat( "MM月dd日" );
                     long  dTime = today.getTime() - tDate.getTime();
                     if  (tDate.before(thisYear)) {
                         display =  new  SimpleDateFormat( "yyyy年MM月dd日" ).format(tDate);
                     else  {
 
                         if  (dTime < tMin) {
                             display =  "刚刚" ;
                         else  if  (dTime < tHour) {
                             display = ( int ) Math.ceil(dTime / tMin) +  "分钟前" ;
                         else  if  (dTime < tDay && tDate.after(yesterday)) {
                             display = ( int ) Math.ceil(dTime / tHour) +  "小时前" ;
                         else  if  (tDate.after(beforeYes) && tDate.before(yesterday)) {
                             display =  "昨天"  new  SimpleDateFormat( "HH:mm" ).format(tDate);
                         else  {
                             display = halfDf.format(tDate);
                         }
                     }
                 }
             catch  (Exception e) {
                 e.printStackTrace();
             }
         }
 
         return  display;
     }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值