Java时间处理之二(xx天前、xx年前)

本文介绍了一个Java程序,用于将字符串格式的时间转换为日期,并计算当前时间与该时间之间的距离,输出为易于理解的短时间表述。

转自http://blog.youkuaiyun.com/feng88724/article/details/7302737

  1. public class test {  
  2.       
  3.     public static Date getDateByString(String time) {  
  4.         Date date = null;  
  5.         if(time == nullreturn date;  
  6.         String date_format = "yyyy-MM-dd HH:mm:ss";  
  7.         SimpleDateFormat format = new SimpleDateFormat(date_format);  
  8.         try {  
  9.             date = format.parse(time);  
  10.         } catch (ParseException e) {  
  11.             e.printStackTrace();  
  12.         }  
  13.         return date;  
  14.     }  
  15.       
  16.     public static String getShortTime(String time) {  
  17.         String shortstring = null;  
  18.         long now = Calendar.getInstance().getTimeInMillis();  
  19.         Date date = getDateByString(time);  
  20.         if(date == nullreturn shortstring;  
  21.         long deltime = (now - date.getTime())/1000;  
  22.         if(deltime > 365*24*60*60) {  
  23.             shortstring = (int)(deltime/(365*24*60*60)) + "年前";  
  24.         } else if(deltime > 24*60*60) {  
  25.             shortstring = (int)(deltime/(24*60*60)) + "天前";  
  26.         } else if(deltime > 60*60) {  
  27.             shortstring = (int)(deltime/(60*60)) + "小时前";  
  28.         } else if(deltime > 60) {  
  29.             shortstring = (int)(deltime/(60)) + "分前";  
  30.         } else if(deltime > 1) {  
  31.             shortstring = deltime + "秒前";  
  32.         } else {  
  33.             shortstring = "1秒前";  
  34.         }  
  35.         return shortstring;  
  36.     }  
  37.       
  38.     public static void main(String[] args) {  
  39.         String time = "2012-02-28 10:40:55";  
  40.         System.out.println(getShortTime(time));  
  41.     }  
  42.       
  43. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值