当前位置 : 主页 > 编程语言 > java >

计算两个时间之间相差多少天,多少小时,多少分钟,多少秒

来源:互联网 收集:自由互联 发布时间:2021-06-28
gistfile1.txt public static Map getTimeDifference(Integer startTime,Integer endTime){Map resMap = new HashMap (); String endTimeStr = String.valueOf(endTime); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String end =
gistfile1.txt
public static Map
 
   getTimeDifference(Integer startTime,Integer endTime){
		Map
  
    resMap = new HashMap
   
    (); String endTimeStr = String.valueOf(endTime); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String end = sdf.format(new Date(Long.valueOf(endTimeStr+"000"))); String startTimeStr = String.valueOf(startTime); String start = sdf.format(new Date(Long.valueOf(startTimeStr+"000"))); long nd = 1000*24*60*60;//一天的毫秒数 long nh = 1000*60*60;//一小时的毫秒数 long nm = 1000*60;//一分钟的毫秒数 long ns = 1000;//一秒钟的毫秒数long //获得两个时间的毫秒时间差异 long diff = 0; try { diff = sdf.parse(end).getTime() - sdf.parse(start).getTime(); } catch (ParseException e) { LogUtil.error(TimeUtil.class, "getTimeDifference", "时间差计算异常", e); } long day = diff/nd;//计算差多少天 long hour = diff%nd/nh;//计算差多少小时 long min = diff%nd%nh/nm;//计算差多少分钟 long sec = diff%nd%nh%nm/ns;//计算差多少秒//输出结果 resMap.put("day", day); resMap.put("hour", hour); resMap.put("min", min); resMap.put("sec", sec); return resMap; }
   
  
 
获取指定时间的时间戳(时间类型为yyyyMMdd)
public static long getSpecifiedTimeStamp(String time) {
		DateFormat df = new SimpleDateFormat("yyyyMMdd");
		long timestamp = 0l;
		try {
			Date date = df.parse(time);
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			timestamp = cal.getTimeInMillis();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return timestamp/1000;
	}
网友评论