자바 계산 두 시간 차이 n 일 n 시간 n 분 n 초 n 밀리초

2147 단어 자바
/**
 *         n n  n  n n  
 *
 */
public static long[] getDistanceTime(Object str1, Object str2) {
      Date one;
      Date two;
      long day = 0;
      long hour = 0;
      long min = 0;
      long sec = 0;
      long ms = 0;
      try {
         one = chgObject(str1);
         two = chgObject(str2);
         long time1 = one.getTime();
         long time2 = two.getTime();
         long diff ;
         if(time1 < time2) {
            diff = time2 - time1;
         } else {
            diff = time1 - time2;
         }
         day = diff / (24 * 60 * 60 * 1000);
         hour = (diff / (60 * 60 * 1000) - day * 24);
         min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
         sec = (diff/1000-day*24*60*60-hour*60*60-min*60);
         ms = (diff - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - sec * 1000);
      } catch (ParseException e) {
         e.printStackTrace();
      }
      long[] data = new long[5];
      data[0] = day;
      data[1] = hour;
      data[2] = min;
      data[3] = sec;
      data[4] = ms;
      return data;
   }

/**
 *  Object     Date yyyy-MM-dd HH:mm:ss
 * @param date
 * @return
 */
public static Date chgObject(Object date) {
    if (date != null && date instanceof Date) {
	return (Date) date;
    }
    if (date != null && date instanceof String) {
	return DateUtils.stringToDate((String) date);
    }
    return null;
}



/**
 *               yyyy-MM-dd HH:mm:ss
 * @param datestr
 * @return
 */
public static Date stringToDate(String datestr) {
    if (datestr == null || datestr.equals("")) {
	return null;
    }
    Date date = new Date();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
	date = df.parse(datestr);
    } catch (ParseException e) {
	date = DateUtils.stringToDate(datestr, "yyyyMMdd");
    }
    return date;
}

 테스트:
public static void main(String[] args) {
		long[] s = getDistanceTime("2020-04-07 14:00:00", "2020-04-14 11:00:00");
		System.err.println(Arrays.toString(s));
	}

 

좋은 웹페이지 즐겨찾기