判断某个时间是否是在条件的起始时间与结束时间之内

判断某个时间是否是在条件时间的n天之内

判断某个时间是否是在条件时间的n天之内

正数表示在条件时间n天之后,负数表示在条件时间n天之前

  /**
     * 判断time是否在now的n天之内
     * @param time
     * @param now
     * @param n    正数表示在条件时间n天之后,负数表示在条件时间n天之前
     * @return
     */
    public static boolean belongDate(Date time, Date now, int n) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();  //得到日历
        calendar.setTime(now);//把当前时间赋给日历
        calendar.add(Calendar.DAY_OF_MONTH, n);
        Date before7days = calendar.getTime();   //得到n前的时间
        if (before7days.getTime() < time.getTime()) {
            return true;
        } else {
            return false;
        }
    }
       //打印测试
        Date time  = stringToDate("2017-3-13");//string转为date
        Date now = new Date();//直接new对象,获取的是当前时间2017-3-16
        System.out.println(belongDate(time,now,-2));//2天前
        System.out.println(belongDate(time,now,2));//2天后
        System.out.println(belongDate(time,now,-6));//6天前

判断某个时间是否是在条件的起始时间与结束时间之内

/**
     * 判断time是否在from,to之内
     *
     * @param time 指定日期
     * @param from 开始日期
     * @param to   结束日期
     * @return
     */
    public static boolean belongCalendar(Date time, Date from, Date to) {
        Calendar date = Calendar.getInstance();
        date.setTime(time);

        Calendar after = Calendar.getInstance();
        after.setTime(from);

        Calendar before = Calendar.getInstance();
        before.setTime(to);

        if (date.after(after) && date.before(before)) {
            return true;
        } else {
            return false;
        }
    }
        //打印测试
        Date time1  = stringToDate("2017-3-11");
        Date time2 = stringToDate("2017-3-15");
        Date time3 = stringToDate("2017-3-17");
        Date from = stringToDate("2017-3-12");
        Date to= stringToDate("2017-3-16");
        System.out.println(belongCalendar(time1,from,to));
        System.out.println(belongCalendar(time2,from,to));
        System.out.println(belongCalendar(time3,from,to)); 

判断给定时间与当前时间相差多少天

   public static long getDistanceDays(String date) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        long days = 0;
        try {
            Date time = df.parse(date);//String转Date
            Date now = new Date();//获取当前时间
            long time1 = time.getTime();
            long time2 = now.getTime();
            long diff = time1 - time2;
            days = diff / (1000 * 60 * 60 * 24);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return days;//正数表示在当前时间之后,负数表示在当前时间之前
    }


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值