java实现mysql的to_days函数,要求输出结果一致
展开全部
mysql的to_days是计算从公元0年到当前日期的时间差,但事实上公元0年是不存在的,所以用java实现的话都有点区别,如果计算两个时间的日差的话,可以用下面的方法
package know;
import java.sql.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class T1 {
public static void main(String[] a) {
System.out.println(getDaysBetween(Date.valueOf("2016-12-01"),
Date.valueOf("2017-02-28")));
}
public static int getDaysBetween(Date start, Date end) {
boolean negative = false;
if (end.before(start)) {
negative = true;
Date temp = start;
start = end;
end = temp;
}
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(start);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
GregorianCalendar calEnd = new GregorianCalendar();
calEnd.setTime(end);
calEnd.set(Calendar.HOUR_OF_DAY, 0);
calEnd.set(Calendar.MINUTE, 0);
calEnd.set(Calendar.SECOND, 0);
calEnd.set(Calendar.MILLISECOND, 0);
if (cal.get(Calendar.YEAR) == calEnd.get(Calendar.YEAR)) {
if (negative)
return (calEnd.get(Calendar.DAY_OF_YEAR) - cal
.get(Calendar.DAY_OF_YEAR)) * -1;
return calEnd.get(Calendar.DAY_OF_YEAR)
- cal.get(Calendar.DAY_OF_YEAR);
}
int counter = 0;
while (calEnd.after(cal)) {
cal.add(Calendar.DAY_OF_YEAR, 1);
counter++;
}
if (negative)
return counter * -1;
return counter;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询