SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd"); Date today = sd.parse(sd.format(new Date())); Date beginDate = new Date(2021,11,15); Date endDate = new Date(2021,12,16); int x = beginDate.compareTo(today); int y = endDate.compareTo(today); System.out.println("x=" + x + ",y=" + y);
如上代码为什么x和y都是1,不该是1和-1吗?
你得到的beginDate和endDate这两个值不是2021年
是3921年
你点进去看一下data的构造函数就知道了
/**
* Allocates a <code>Date</code> object and initializes it so that
* it represents midnight, local time, at the beginning of the day
* specified by the <code>year</code>, <code>month</code>, and
* <code>date</code> arguments.
*
* @param year the year minus 1900.
* @param month the month between 0-11.
* @param date the day of the month between 1-31.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.set(year + 1900, month, date)</code>
* or <code>GregorianCalendar(year + 1900, month, date)</code>.
*/
@Deprecated
public Date(int year, int month, int date) {
this(year, month, date, 0, 0, 0);
}
看这里 年份的入参应该是你的年份-1990,而且这个方法已经弃用了就不要再用了
@param year the year minus 1900.
还有月份入参 应该是0-11 你穿了12的用法也是不对的
@param month the month between 0-11.
好吧,感谢,服服服,这么多坑