/** * java時間戳是13位的,php後臺是10位的,因此要截斷 */ private static long timestampConvent(long stamp) { String temp = stamp + ""; return Long.parseLong(temp.substring(0, 10)); } /** * 獲取今天的時間戳 */ public static long getNowTimeStamp() { return timestampConvent(new Date().getTime()); } /** * 獲取明天的時間戳 */ public static long getTomorrowTimeStamp() { Calendar tomrrow = Calendar.getInstance(); tomrrow.add(Calendar.DAY_OF_MONTH, 1); return timestampConvent(tomrrow.getTime().getTime()); } /** * 獲取指定時間的時間戳 */ public static long getTimeStamp(String time, String format) { Date date; //注意format的格式要與日期String的格式相匹配 DateFormat sdf = new SimpleDateFormat(format, Locale.CHINA); try { date = sdf.parse(time); } catch (Exception e) { e.printStackTrace(); return -1; } return timestampConvent(date.getTime()); } /** * 把時間戳轉爲閱讀友好的字符串 * * @param time 10位時間戳,由於服務器端傳過來的是10位,因此在android裏面使用時須要*1000增長到13位 */ public static String getFormatTime(long time) { Calendar target = Calendar.getInstance(); target.setTime(new Date(time * 1000)); String format = "yyyy年MM月dd日 HH:mm:ss"; Calendar today = Calendar.getInstance(); if (today.get(Calendar.YEAR) == target.get(Calendar.YEAR) && today.get(Calendar.MONTH) == target.get(Calendar.MONTH) && today.get(Calendar.DAY_OF_MONTH) == target.get(Calendar.DAY_OF_MONTH)) { //今天 if (target.get(Calendar.HOUR_OF_DAY) < 3) { format = "凌晨 HH:mm:ss"; } else if (target.get(Calendar.HOUR_OF_DAY) < 12) { format = "上午 HH:mm:ss"; } else if (target.get(Calendar.HOUR_OF_DAY) < 18) { format = "下午 HH:mm:ss"; } else { format = "晚上 HH:mm:ss"; } } else { target.add(Calendar.DAY_OF_MONTH, 1);//加1,若是時間爲昨天的話,加1以後的時間就是今天了 if (today.get(Calendar.YEAR) == target.get(Calendar.YEAR) && today.get(Calendar.MONTH) == target.get(Calendar.MONTH) && today.get(Calendar.DAY_OF_MONTH) == target.get(Calendar.DAY_OF_MONTH)) { //昨天 format = "昨天 HH:mm:ss"; } else { target.setTime(new Date(time * 1000)); if (target.get(Calendar.YEAR) == today.get(Calendar.YEAR)) { format = "MM月dd日 HH:mm:ss"; } } } return StaticMethod.timestampToString(time + "", format); } /** * 10位時間戳轉換爲指定格式的時間字符串 */ public static String timestampToString(String time, String format) { if (time.length() > 3) { long temp = Long.parseLong(time) * 1000; Timestamp ts = new Timestamp(temp); String tsStr = ""; DateFormat dateFormat = new SimpleDateFormat(format, Locale.CHINA); try { tsStr = dateFormat.format(ts); System.out.println(tsStr); } catch (Exception e) { e.printStackTrace(); } return tsStr; } else { return ""; } }