首页 新闻 会员 周边

java中如何比较时间

0
悬赏园豆:50 [已解决问题] 解决于 2021-11-16 15:16
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吗?

空明流光的主页 空明流光 | 初学一级 | 园豆:106
提问于:2021-11-16 14:55
< >
分享
最佳答案
0

你得到的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.
收获园豆:50
蓝羽code | 菜鸟二级 |园豆:313 | 2021-11-16 15:11

好吧,感谢,服服服,这么多坑

空明流光 | 园豆:106 (初学一级) | 2021-11-16 15:16
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册