Java时间处理 将时间戳转换为“几天前”的格式
做项目的时候,我们经常会遇到将数据库生成的long型类似1335189486形式的时间戳和当前时间对比,显示为新浪微博中显示的“几天前”,“几秒前”的格式,以下是解决方法。闲话少活,先上代码:
1 /** 2 * project : Test 3 * 4 * 5 *=========================================================== 6 * amend date amend user amend reason 7 * 2012-4-28 Zhang Xiaowen create this file 8 */ 9 10 /** 11 * @file_name Test.java 12 * 13 * @author Zhang Xiaowen(zxw.wen@gmail.com) 14 * @create 2012-4-28 15 * @TODO 16 */ 17 import java.sql.Timestamp; 18 import java.text.ParseException; 19 import java.text.SimpleDateFormat; 20 import java.util.Calendar; 21 import java.util.Date; 22 23 public class Test { 24 25 public static Date getDateByString(String time) { 26 Date date = null; 27 if (time == null) 28 return date; 29 String date_format = "yyyy-MM-dd HH:mm:ss"; 30 SimpleDateFormat format = new SimpleDateFormat(date_format); 31 try { 32 date = format.parse(time); 33 } catch (ParseException e) { 34 e.printStackTrace(); 35 } 36 return date; 37 } 38 39 public static String getShortTime(long dateline) { 40 String shortstring = null; 41 String time = timestampToStr(dateline); 42 Date date = getDateByString(time); 43 if(date == null) return shortstring; 44 45 long now = Calendar.getInstance().getTimeInMillis(); 46 long deltime = (now - date.getTime())/1000; 47 if(deltime > 365*24*60*60) { 48 shortstring = (int)(deltime/(365*24*60*60)) + "年前"; 49 } else if(deltime > 24*60*60) { 50 shortstring = (int)(deltime/(24*60*60)) + "天前"; 51 } else if(deltime > 60*60) { 52 shortstring = (int)(deltime/(60*60)) + "小时前"; 53 } else if(deltime > 60) { 54 shortstring = (int)(deltime/(60)) + "分前"; 55 } else if(deltime > 1) { 56 shortstring = deltime + "秒前"; 57 } else { 58 shortstring = "1秒前"; 59 } 60 return shortstring; 61 } 62 63 //Timestamp转化为String: 64 public static String timestampToStr(long dateline){ 65 Timestamp timestamp = new Timestamp(dateline*1000); 66 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式,不显示毫秒 67 return df.format(timestamp); 68 } 69 70 71 public static void main(String[] args) { 72 long dateline = 1335189486; 73 System.out.println(getShortTime(dateline)); 74 // String time = "2012-04-20 10:40:55"; 75 // System.out.println(getShortTime(time)); 76 } 77 78 }
运行结果,输出:
5天前