1
package com.test.util; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class MyDate { /** * ThreadLocal可以给一个初始值,而每个线程都会获得这个初始化值的一个副本,这样才能保证不同的线程都有一份拷贝。 ThreadLocal * 不是用于解决共享变量的问题的 * 不是为了协调线程同步而存在,而是为了方便每个线程处理自己的状态而引入的一个机制,理解这点对正确使用ThreadLocal至关重要。 */ private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { //注意这里返回值是一个新建对象,而不是一个在此方法外面的既存对象,那样会不管用 //引用的副本和引用指向的是同一个对象 return new SimpleDateFormat("yyyy-MM-dd"); } }; /** * 以友好的方式显示时间 * * @param sdate * @return */ public static String friendly_time(Date time) { if (time == null) { return "Unknown"; } String ftime = ""; Calendar cal = Calendar.getInstance(); // 判断是否是同一天 String curDate = dateFormater2.get().format(cal.getTime()); String paramDate = dateFormater2.get().format(time); if (curDate.equals(paramDate)) { int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000); if (hour == 0) ftime = Math.max( (cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前"; else ftime = hour + "小时前"; return ftime; } long lt = time.getTime() / 86400000; long ct = cal.getTimeInMillis() / 86400000; int days = (int) (ct - lt); if (days == 0) { int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000); if (hour == 0) ftime = Math.max( (cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前"; else ftime = hour + "小时前"; } else if (days == 1) { ftime = "昨天"; } else if (days == 2) { ftime = "前天"; } else if (days > 2 && days <= 10) { ftime = days + "天前"; } else if (days > 10) { ftime = dateFormater2.get().format(time); } return ftime; } /** * 将字符串转位日期类型 * * @param sdate * @return */ public static Date toDate(String sdate) { try { return dateFormater2.get().parse(sdate); } catch (java.text.ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } }
Done