标签:style class blog c code java
1 package com.tai.use; 2 3 import java.text.DateFormat; 4 import java.text.SimpleDateFormat; 5 import java.util.Calendar; 6 import java.util.Date; 7 8 public class GuiYI 9 { 10 /** 11 * GuiYI 诡异的需求 12 * 转为 n秒前 n分钟前 n小时前 日期 13 * @param time 14 * @param format 很长时间前显示的日期格式 15 * @return 16 */ 17 public static String dataLongToSNS(long time,String format){ 18 long now = System.currentTimeMillis(); 19 20 long diff = now -time; 21 diff = diff/1000;// 秒 22 23 if(diff<0){ 24 return dateLongToString(time,format); 25 } 26 27 if(diff<30){ // 30秒 28 return "刚刚"; 29 } 30 31 if(diff<60){ 32 return String.format("%s秒前", diff); 33 } 34 35 if(diff<3600){ 36 return String.format("%s分钟前", diff/60); 37 } 38 //获取今天凌晨时间 39 long todayStart = getMoring(new Date()).getTime(); 40 41 if(time>=todayStart){// 今天 42 return String.format("%s小时前", diff/3600); 43 } 44 45 if(time<todayStart && time >= todayStart-86400000){ 46 return "昨天 " + dateLongToString(time, "HH:mm"); 47 } 48 49 return dateLongToString(time,format); 50 } 51 //获取今天凌晨的时间 52 private static Date getMoring(Date date) 53 { 54 Calendar calendar = Calendar.getInstance(); 55 calendar.setTime(date); 56 calendar.set(Calendar.HOUR_OF_DAY, 0); 57 calendar.set(Calendar.MINUTE, 0); 58 calendar.set(Calendar.SECOND, 0); 59 return calendar.getTime(); 60 } 61 public static String dateLongToString(long time){ 62 return dateLongToString(time,null); 63 } 64 public static String dateLongToString(long time,String format){ 65 if(time<=0){ 66 return "Empty"; 67 } 68 DateFormat format2 = new SimpleDateFormat(format); 69 String dateString = format2.format(new Date(time)); 70 return dateString; 71 } 72 73 public static void main(String[] args) 74 { 75 System.out.println(dataLongToSNS(1400837178603L,"yyyy-MM-dd HH:mm:ss")); 76 } 77 }
long类型的时间转为n秒前n分钟前n小时前或者日期,布布扣,bubuko.com
标签:style class blog c code java
原文地址:http://www.cnblogs.com/mauiie/p/3748224.html