package api.common.util; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class TimeUtil { private static String[] dateFmtArr = new String[]{"yyyyMMdd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", "HHmmssSS", "HH:mm:ss", "yyyyMMddHHmmss"}; public static long getNow() { return System.currentTimeMillis(); } public static long getNowLong() { return System.currentTimeMillis(); } public static String getNowString() { return System.currentTimeMillis() + ""; } public static Timestamp getNowForMysql() { return new Timestamp(System.currentTimeMillis()); } public static long zeroOfToday() { return System.currentTimeMillis() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset(); } //获取时间类型格式转化 public static Integer getRq(Date date, int index) { SimpleDateFormat sdf = new SimpleDateFormat(dateFmtArr[index]); if (date == null) { date = new Date(); } return Integer.valueOf(sdf.format(date)); } //获取时间类型格式转化 public static String getToStringDate(Date date, int index) { SimpleDateFormat sdf = new SimpleDateFormat(dateFmtArr[index]); if (date == null) { date = new Date(); } return sdf.format(date); } //获取过去某天的起始日期 public static Map getPastTime(Integer num) { Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.add(Calendar.DATE, -num); Date d = c.getTime(); String startDate = getToStringDate(d, 2) + " 00:00:00"; String endDate = getToStringDate(d, 2) + " 23:59:59"; Map map = new HashMap(); map.put("startDate", startDate); map.put("endDate", endDate); map.put("toDate", getToStringDate(d, 2)); return map; } //获取间隔 n 秒的时间 public static Timestamp getPostTimestamp(int secends) { return new Timestamp(System.currentTimeMillis() + secends * 1000); } //获取两个时间间隔 public static String getTimeDifference(Date dateStart, Date dateStop) { String message = ""; try { //毫秒ms long diff = dateStop.getTime() - dateStart.getTime(); long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000) % 24; long diffDays = diff / (24 * 60 * 60 * 1000); if (diffDays > 0) { message = diffDays + "天" + diffHours + "小时" + diffMinutes + "分钟" + diffSeconds + "秒"; } else if (diffDays == 0 && diffHours != 0) { message = diffHours + "小时" + diffMinutes + "分钟" + diffSeconds + "秒"; } else if (diffDays == 0 && diffHours == 0 && diffMinutes != 0) { message = diffMinutes + "分钟" + diffSeconds + "秒"; } else if (diffDays == 0 && diffHours == 0 && diffMinutes == 0 && diffSeconds != 0) { message = diffSeconds + "秒"; } } catch (Exception e) { e.printStackTrace(); } return message; } }