java实现mysql的to_days函数,要求输出结果一致
发布网友
发布时间:2022-05-02 20:03
我来回答
共3个回答
懂视网
时间:2022-05-03 00:25
热心网友
时间:2022-05-02 21:33
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;
}
}
热心网友
时间:2022-05-02 22:51
//最简单的办法
//在select TO_DAYS('1970-01-01')的结果是719528
long millis = System.currentTimeMillis();
//今天距1970-01-01的天数
long nowDays = millis / 1000 / 60 / 60 / 24;
//所以nowDays + 719528 的结果等同于 TO_DAYS(NOW())