数据库查询出的开始结束时间相减,获得时间差,转为xx天xx时xx分
程序员文章站
2024-01-29 10:29:58
...
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql); //我的list格式是list<map>类型的 可以按需自己调整
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //规定获得的日期格式 与数据库存储的类型一致
for (int i = 0;i<list.size();i++) {
Object timeofend = list.get(i).get("ENDTIME");
if(null==timeofend||"".equals(timeofend)){ //如果结束时间为空的话直接跳过,不转化
System.out.println("null---"+timeofend);
list.get(i).put("timecha", ""); //要传到前台的
}else{
System.out.println("not null---"+timeofend);
Date dateTimeend = sdf.parse(String.valueOf(timeofend));
String starttime = String.valueOf(list.get(i).get("STARTTIME"));
Date dateTimeStart =sdf.parse(starttime);
long timecha = dateTimeend.getTime()-dateTimeStart.getTime();//获得时间差
double daytime = Math.floor(timecha/(24 * 60 * 60 * 1000));
int day=(int)Math.floor(daytime);//转化天
double housess = timecha % (1000 * 60 * 60 * 24) / (1000 * 60 * 60);
int house = (int) Math.floor(housess);//转化小时
double mi = timecha % (1000 * 60 * 60) / (1000 * 60);
int minutes = (int) Math.floor(mi);//转化分钟
System.out.println(day + "天" + house + "小时" + minutes + "分");
if(day>0){
list.get(i).put("timecha", day + "天" + house + "小时" + minutes + "分");
}else{
if(house>0){
list.get(i).put("timecha", house + "小时" + minutes + "分");
}else{
list.get(i).put("timecha", minutes + "分");
}
}