·软件知识库 ·模板素材库
注册 | 登录

您所在的位置: INDEX > j2se > java计算两个日期相差多少天小时分钟等

java计算两个日期相差多少天小时分钟等

许杰 Sun Jul 05 12:01:51 CST 2015 字号:

1、时间转换

data默认有toString() 输出格林威治时间,比如说Date date = new Date(); String toStr = date.toString(); 输出的结果类似于: Wed Sep 16 19:02:36 CST 2012 你要输出yyyy-MM-dd hh:mm:ss这种格式的话, 使用SimpleDataFormat类 比如 Date date = new Date(); String dateStr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date); System.out.println(dateStr); 输出结果像下面这样: 2009-09-16 07:02:36当然啦,你也可以把:hh:mm:ss去掉,输出的结果也就只有年-月-日了

2、时间差

public static String getDatePoor(Date endDate, Date nowDate) {

   long nd = 1000 * 24 * 60 * 60;
   long nh = 1000 * 60 * 60;
   long nm = 1000 * 60;
   // long ns = 1000;
   // 获得两个时间的毫秒时间差异
   long diff = endDate.getTime() - nowDate.getTime();
   // 计算差多少天
   long day = diff / nd;
   // 计算差多少小时
   long hour = diff % nd / nh;
   // 计算差多少分钟
   long min = diff % nd % nh / nm;
   // 计算差多少秒//输出结果
   // long sec = diff % nd % nh % nm / ns;
   return day + "天" + hour + "小时" + min + "分钟";
}




『相关搜索』
版本信息:kms v1.3 鄂ICP备2023004815号-1 51LA统计