两时间差

/**
* @Comments:返回时间差
* @param 两个字符串类型的时间差(time1-time2),type(D天,H时,M分,S秒,Z-S天时分秒)
* @return
*/

public final static SimpleDateFormat SF_SIZE19 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//初始化时间格式
public static String toTimeSub(String time1, String time2,String type) {
  long days=0,hours=0,minutes=0,seconds=0;
  String str = "";
  try {
    Date d1 = SF_SIZE19.parse(time1);
    Date d2 = SF_SIZE19.parse(time2);
    long diff = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别
    if(type.equals("D")){
      str = String.valueOf(diff/(1000 * 60 * 60 * 24));
    }else if(type.equals("H")){
      str = String.valueOf(diff /(1000 * 60 * 60));
    }else if(type.equals("M")){
      str = String.valueOf(diff/(1000 * 60));
    }else if(type.equals("S")){
      str = String.valueOf(diff/1000);
    }else if(type.equals("Z-S")){
      days = diff/(1000 * 60 * 60 * 24);
      hours = (diff - days * (1000 * 60 * 60 * 24))/(1000 * 60 * 60);
      minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60))/(1000 * 60);
      seconds = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60) - minutes * (1000 * 60))/1000;
      str = days+"天"+hours+"小时"+minutes+"分"+seconds+"秒";
    }
  } catch (Exception e) {
    toThExCla(e, "Constant");
  }
  return str;
}

posted @ 2016-12-29 10:31  dyf423  阅读(524)  评论(0)    收藏  举报