码迷,mamicode.com
首页 > 数据库 > 详细

用java实现sql server中的datediff函数

时间:2014-10-31 20:30:31      阅读:549      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   ar   java   sp   div   on   art   

 
1
/** 2 * 计算两个时间的相差值, 可以计算相差的天数, 年数, 月份数, 分钟数, 秒数 3 * 4 * @param dateType 要得到的两个时间之间差值的类型, 例如要得到两个时间差的天数?还是小时数? 5 * @param startDate 开始时间 6 * @param endDate 结束时间 7 * @return (结束时间-开始时间) 之间的 dateType值 8 */ 9 public static int datediff(String dateType, Date startDate, Date endDate) { 10 11 /* 求startDate与endDate之间相差的年数 */ 12 if ("y".equalsIgnoreCase(dateType) || "yy".equalsIgnoreCase(dateType)) { 13 Calendar calendar = Calendar.getInstance(); 14 calendar.setTime(startDate); 15 int startYear = calendar.get(Calendar.YEAR); //当前年的年份 16 calendar.setTime(endDate); 17 int endYear = calendar.get(Calendar.YEAR); 18 return endYear - startYear; 19 } 20 /* 求startDate与endDate之间相差的月份数 */ 21 if ("M".equals(dateType) || "MM".equals(dateType)){ 22 Calendar calendar = Calendar.getInstance(); 23 calendar.setTime(startDate); 24 int startMonth = calendar.get(Calendar.MONTH)+calendar.get(Calendar.YEAR)*12; // 月份= 当前年的年份*12 + 当前年的月份, 下同 25 calendar.setTime(endDate); 26 int endMonth = calendar.get(Calendar.MONTH)+calendar.get(Calendar.YEAR)*12; 27 return endMonth - startMonth; 28 } 29 /* 求startDate与endDate之间相差的天数 */ 30 if ("d".equalsIgnoreCase(dateType) || "dd".equalsIgnoreCase(dateType)) { 31 long startTime = startDate.getTime(); 32 long endTime = endDate.getTime(); 33 return (int) ((endTime - startTime) / 1000 / 60 / 60 / 24); // 天数 = (结束时间-开始时间)之间的毫秒数 / (一天拥有的毫秒数) 34 } 35 /* 求startDate与endDate之间相差的小时数 */ 36 if ("h".equalsIgnoreCase(dateType) || "hh".equalsIgnoreCase(dateType)) { 37 long startTime = startDate.getTime(); 38 long endTime = endDate.getTime(); 39 return (int) ((endTime - startTime) / 1000 / 60 / 60); 40 } 41 /* 求startDate与endDate之间相差的分钟数 */ 42 if ("m".equals(dateType) || "mm".equals(dateType)) { 43 long startTime = startDate.getTime(); 44 long endTime = endDate.getTime(); 45 return (int) ((endTime - startTime) / 1000 / 60); 46 } 47 /* 求startDate与endDate之间相差的秒数 */ 48 if ("s".equalsIgnoreCase(dateType) || "ss".equalsIgnoreCase(dateType)) { 49 long startTime = startDate.getTime(); 50 long endTime = endDate.getTime(); 51 return (int) ((endTime - startTime) / 1000); 52 } 53 54 return 0; 55 56 }

 

用java实现sql server中的datediff函数

标签:style   blog   color   ar   java   sp   div   on   art   

原文地址:http://www.cnblogs.com/klaus-guan/p/4065762.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!