Java Code Examples for cn.hutool.core.date.DateUtil#between()

The following examples show how to use cn.hutool.core.date.DateUtil#between() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BlockDataResetService.java    From WeBASE-Collect-Bee with Apache License 2.0 6 votes vote down vote up
public CommonResponse resetBlockDataByBlockId(long blockHeight) throws IOException {

        Optional<BlockTaskPool> blockTaskPool = blockTaskPoolRepository.findByBlockHeight(blockHeight);
        if (!blockTaskPool.isPresent()) {
            return CommonResponse.NOBLOCK;
        }
        if (blockTaskPool.get().getSyncStatus() == TxInfoStatusEnum.DOING.getStatus()) {
            return ResponseUtils.error("Some task is still running. please resend the request later.");
        }
        if (blockTaskPool.get().getSyncStatus() == TxInfoStatusEnum.RESET.getStatus()) {
            if (DateUtil.between(blockTaskPool.get().getDepotUpdatetime(), DateUtil.date(), DateUnit.SECOND) < 60) {
                return ResponseUtils.error("The block is already in progress to reset. please send the request later");
            }
        }
        log.info("begin to refetch block {}", blockHeight);
        blockTaskPoolRepository.setSyncStatusByBlockHeight((short) TxInfoStatusEnum.RESET.getStatus(), new Date(),
                blockHeight);
        rollBackService.rollback(blockHeight, blockHeight + 1);
        singleBlockCrawlerService.parse(blockHeight);
        blockTaskPoolRepository.setSyncStatusByBlockHeight((short) TxInfoStatusEnum.DONE.getStatus(), new Date(),
                blockHeight);
        log.info("block {} is reset!", blockHeight);
        return ResponseUtils.success();
    }
 
Example 2
Source File: SysConfigServiceImpl.java    From OneBlog with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取网站详情
 */
@Override
public Map<String, Object> getSiteInfo() {
    Map<String, Object> siteInfo = sysConfigMapper.getSiteInfo();
    if (!CollectionUtils.isEmpty(siteInfo)) {
        Date installdate = null;
        SysConfig config = this.getByKey(ConfigKeyEnum.INSTALLDATE.getKey());
        if (null == config || StringUtils.isEmpty(config.getConfigValue())) {
            // 默认建站日期为2019-01-01
            installdate = Date.from(LocalDate.of(2019, 1, 1).atStartOfDay(ZoneId.systemDefault()).toInstant());
        } else {
            installdate = DateUtil.parse(config.getConfigValue(), DatePattern.NORM_DATETIME_PATTERN);
        }
        long between = 1;
        if (!installdate.after(new Date())) {
            between = DateUtil.between(installdate, new Date(), DateUnit.DAY);
        }
        siteInfo.put("installdate", between < 1 ? 1 : between);
    }
    return siteInfo;
}
 
Example 3
Source File: JvmInfo.java    From Guns with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * JDK运行时间
 */
public String getRunTime() {

    long time = ManagementFactory.getRuntimeMXBean().getStartTime();
    Date date = new Date(time);

    //运行多少分钟
    long runMS = DateUtil.between(date, new Date(), DateUnit.MS);

    long nd = 1000 * 24 * 60 * 60;
    long nh = 1000 * 60 * 60;
    long nm = 1000 * 60;

    long day = runMS / nd;
    long hour = runMS % nd / nh;
    long min = runMS % nd % nh / nm;

    return day + "天" + hour + "小时" + min + "分钟";
}
 
Example 4
Source File: CountServiceImpl.java    From BigDataPlatform with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 无数据补0
 * @param startTime
 * @param endTime
 */
public List<OrderChartData> getFullData(List<OrderChartData> data,Date startTime, Date endTime){

    List<OrderChartData> fullData = new ArrayList<>();
    //相差
    long betweenDay = DateUtil.between(startTime, endTime, DateUnit.DAY);
    //起始时间
    Date everyday = startTime;
    int count = -1;
    for(int i=0;i<=betweenDay;i++){
        boolean flag = true;
        for(OrderChartData chartData:data){
            if(DateUtils.isSameDay(chartData.getTime(),everyday)){
                //有数据
                flag = false;
                count++;
                break;
            }
        }
        if(!flag){
            fullData.add(data.get(count));
        }else{
            OrderChartData orderChartData = new OrderChartData();
            orderChartData.setTime(everyday);
            orderChartData.setMoney(new BigDecimal("0"));
            fullData.add(orderChartData);
        }

        //时间+1天
        Calendar cal = Calendar.getInstance();
        cal.setTime(everyday);
        cal.add(Calendar.DAY_OF_MONTH, 1);
        everyday = cal.getTime();
    }
    return fullData;
}
 
Example 5
Source File: AdminController.java    From stone with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 请求后台页面
 *
 * @param model   model
 * @param session session
 *
 * @return 模板路径admin/admin_index
 */
@GetMapping(value = {"", "/index"})
public String index(Model model) {

    //查询评论的条数
    final Long commentCount = commentService.getCount();
    model.addAttribute("commentCount", commentCount);

    //查询最新的文章
    final List<Post> postsLatest = postService.findPostLatest();
    model.addAttribute("postTopFive", postsLatest);

    //查询最新的日志
    final List<Logs> logsLatest = logsService.findLogsLatest();
    model.addAttribute("logs", logsLatest);

    //查询最新的评论
    final List<Comment> comments = commentService.findCommentsLatest();
    model.addAttribute("comments", comments);

    //附件数量
    model.addAttribute("mediaCount", attachmentService.getCount());

    //文章阅读总数
    final Long postViewsSum = postService.getPostViews();
    model.addAttribute("postViewsSum", postViewsSum);

    //成立天数
    final Date blogStart = DateUtil.parse(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_START.getProp()));
    final long hadDays = DateUtil.between(blogStart, DateUtil.date(), DateUnit.DAY);
    model.addAttribute("hadDays", hadDays);
    return "admin/admin_index";
}
 
Example 6
Source File: HutoolController.java    From mall-learning with Apache License 2.0 5 votes vote down vote up
@ApiOperation("DateUtil使用:日期时间工具")
@GetMapping(value = "/dateUtil")
public CommonResult dateUtil() {
    //Date、long、Calendar之间的相互转换
    //当前时间
    Date date = DateUtil.date();
    //Calendar转Date
    date = DateUtil.date(Calendar.getInstance());
    //时间戳转Date
    date = DateUtil.date(System.currentTimeMillis());
    //自动识别格式转换
    String dateStr = "2017-03-01";
    date = DateUtil.parse(dateStr);
    //自定义格式化转换
    date = DateUtil.parse(dateStr, "yyyy-MM-dd");
    //格式化输出日期
    String format = DateUtil.format(date, "yyyy-MM-dd");
    //获得年的部分
    int year = DateUtil.year(date);
    //获得月份,从0开始计数
    int month = DateUtil.month(date);
    //获取某天的开始、结束时间
    Date beginOfDay = DateUtil.beginOfDay(date);
    Date endOfDay = DateUtil.endOfDay(date);
    //计算偏移后的日期时间
    Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
    //计算日期时间之间的偏移量
    long betweenDay = DateUtil.between(date, newDate, DateUnit.DAY);
    return CommonResult.success(null, "操作成功");
}
 
Example 7
Source File: AdminController.java    From blog-sharon with Apache License 2.0 5 votes vote down vote up
/**
 * 请求后台页面
 *
 * @param model   model
 * @param session session
 * @return 模板路径admin/admin_index
 */
@GetMapping(value = {"", "/index"})
public String index(Model model) {

    //查询评论的条数
    Long commentCount = commentService.getCount();
    model.addAttribute("commentCount", commentCount);

    //查询最新的文章
    List<Post> postsLatest = postService.findPostLatest();
    model.addAttribute("postTopFive", postsLatest);

    //查询最新的日志
    List<Logs> logsLatest = logsService.findLogsLatest();
    model.addAttribute("logs", logsLatest);

    //查询最新的评论
    List<Comment> comments = commentService.findCommentsLatest();
    model.addAttribute("comments", comments);

    //附件数量
    model.addAttribute("mediaCount", attachmentService.getCount());

    //文章阅读总数
    Long postViewsSum = postService.getPostViews();
    model.addAttribute("postViewsSum", postViewsSum);

    //成立天数
    Date blogStart = DateUtil.parse(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_START.getProp()));
    long hadDays = DateUtil.between(blogStart, DateUtil.date(), DateUnit.DAY);
    model.addAttribute("hadDays",hadDays);
    return "admin/admin_index";
}
 
Example 8
Source File: NormalRealm.java    From SENS with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 认证信息(身份验证) Authentication 是用来验证用户身份
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    log.info("认证-->MyShiroRealm.doGetAuthenticationInfo()");
    //1.验证用户名
    User user = null;
    String account = (String) token.getPrincipal();
    if (Validator.isEmail(account)) {
        user = userService.findByEmail(account);
    } else {
        user = userService.findByUserName(account);
    }
    if (user == null) {
        //用户不存在
        log.info("用户不存在! 登录名:{}, 密码:{}", account, token.getCredentials());
        return null;
    }

    //2.判断账号是否被封号
    if (!Objects.equals(user.getStatus(), UserStatusEnum.NORMAL.getCode())) {
        throw new LockedAccountException(localeMessageUtil.getMessage("code.admin.login.disabled.forever"));
    }

    //3.首先判断是否已经被禁用已经是否已经过了10分钟
    Date loginLast = DateUtil.date();
    if (null != user.getLoginLast()) {
        loginLast = user.getLoginLast();
    }
    Long between = DateUtil.between(loginLast, DateUtil.date(), DateUnit.MINUTE);
    if (StringUtils.equals(user.getLoginEnable(), TrueFalseEnum.FALSE.getValue()) && (between < CommonParamsEnum.TEN.getValue())) {
        log.info("账号已锁定! 登录名:{}, 密码:{}", account, token.getCredentials());
        throw new LockedAccountException(localeMessageUtil.getMessage("code.admin.login.disabled"));
    }
    //4.封装authenticationInfo,准备验证密码
    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
            user, // 用户名
            user.getUserPass(), // 密码
            ByteSource.Util.bytes("sens"), // 盐
            getName() // realm name
    );
    System.out.println("realName:" + getName());
    return authenticationInfo;
}
 
Example 9
Source File: SignAuthFilter.java    From spring-boot-demo with MIT License 4 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    // 防止流读取一次后就没有了, 所以需要将流继续写出去
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletRequest requestWrapper = new RequestWrapper(httpRequest);

    Set<String> uriSet = new HashSet<>(securityProperties.getIgnoreSignUri());
    String requestUri = httpRequest.getRequestURI();
    boolean isMatch = false;
    for (String uri : uriSet) {
        isMatch = requestUri.contains(uri);
        if (isMatch) {
            break;
        }
    }
    log.info("当前请求的URI是==>{},isMatch==>{}", httpRequest.getRequestURI(), isMatch);
    if (isMatch) {
        filterChain.doFilter(requestWrapper, response);
        return;
    }

    String sign = requestWrapper.getHeader("Sign");
    Long timestamp = Convert.toLong(requestWrapper.getHeader("Timestamp"));

    if (StrUtil.isEmpty(sign)) {
        returnFail("签名不允许为空", response);
        return;
    }

    if (timestamp == null) {
        returnFail("时间戳不允许为空", response);
        return;
    }

    //重放时间限制(单位分)
    Long difference = DateUtil.between(DateUtil.date(), DateUtil.date(timestamp * 1000), DateUnit.MINUTE);
    if (difference > securityProperties.getSignTimeout()) {
        returnFail("已过期的签名", response);
        log.info("前端时间戳:{},服务端时间戳:{}", DateUtil.date(timestamp * 1000), DateUtil.date());
        return;
    }

    boolean accept = true;
    SortedMap<String, String> paramMap;
    switch (requestWrapper.getMethod()) {
        case "GET":
            paramMap = HttpUtil.getUrlParams(requestWrapper);
            accept = SignUtil.verifySign(paramMap, sign, timestamp);
            break;
        case "POST":
        case "PUT":
        case "DELETE":
            paramMap = HttpUtil.getBodyParams(requestWrapper);
            accept = SignUtil.verifySign(paramMap, sign, timestamp);
            break;
        default:
            accept = true;
            break;
    }
    if (accept) {
        filterChain.doFilter(requestWrapper, response);
    } else {
        returnFail("签名验证不通过", response);
    }
}
 
Example 10
Source File: AdminController.java    From stone with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 验证登录信息
 *
 * @param loginName 登录名:邮箱/用户名
 * @param loginPwd  loginPwd 密码
 * @param session   session session
 *
 * @return JsonResult JsonResult
 */
@PostMapping(value = "/getLogin")
@ResponseBody
public JsonResult getLogin(@ModelAttribute("loginName") String loginName,
                           @ModelAttribute("loginPwd") String loginPwd,
                           HttpSession session) {
    //已注册账号,单用户,只有一个
    final User aUser = userService.findUser();
    //首先判断是否已经被禁用已经是否已经过了10分钟
    Date loginLast = DateUtil.date();
    if (null != aUser.getLoginLast()) {
        loginLast = aUser.getLoginLast();
    }
    final Long between = DateUtil.between(loginLast, DateUtil.date(), DateUnit.MINUTE);
    if (StrUtil.equals(aUser.getLoginEnable(), TrueFalseEnum.FALSE.getDesc()) && (between < CommonParamsEnum.TEN.getValue())) {
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.disabled"));
    }
    //验证用户名和密码
    User user = null;
    if (Validator.isEmail(loginName)) {
        user = userService.userLoginByEmail(loginName, SecureUtil.md5(loginPwd));
    } else {
        user = userService.userLoginByName(loginName, SecureUtil.md5(loginPwd));
    }
    userService.updateUserLoginLast(DateUtil.date());
    //判断User对象是否相等
    if (ObjectUtil.equal(aUser, user)) {
        session.setAttribute(HaloConst.USER_SESSION_KEY, aUser);
        //重置用户的登录状态为正常
        userService.updateUserNormal();
        logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_SUCCESS, request);
        log.info("User {} login succeeded.", aUser.getUserDisplayName());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.login.success"));
    } else {
        //更新失败次数
        final Integer errorCount = userService.updateUserLoginError();
        //超过五次禁用账户
        if (errorCount >= CommonParamsEnum.FIVE.getValue()) {
            userService.updateUserLoginEnable(TrueFalseEnum.FALSE.getDesc());
        }
        logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_ERROR + "[" + HtmlUtil.escape(loginName) + "," + HtmlUtil.escape(loginPwd) + "]", request);
        final Object[] args = {(5 - errorCount)};
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.failed", args));
    }
}
 
Example 11
Source File: SysLogHandle.java    From mogu_blog_v2 with Apache License 2.0 4 votes vote down vote up
@Override
protected void onRun() {

    SysLog sysLog = new SysLog();

    HttpServletRequest request = RequestHolder.getRequest();
    String ip = IpUtils.getIpAddr(request);
    sysLog.setIp(ip);

    //从Redis中获取IP来源
    String jsonResult = redisUtil.get(SysConf.IP_SOURCE + BaseSysConf.REDIS_SEGMENTATION + ip);
    if (StringUtils.isEmpty(jsonResult)) {
        String addresses = IpUtils.getAddresses(SysConf.IP + SysConf.EQUAL_TO + ip, SysConf.UTF_8);
        if (StringUtils.isNotEmpty(addresses)) {
            sysLog.setIpSource(addresses);
            redisUtil.setEx(SysConf.IP_SOURCE + BaseSysConf.REDIS_SEGMENTATION + ip, addresses, 24, TimeUnit.HOURS);
        }
    } else {
        sysLog.setIpSource(jsonResult);
    }

    //设置请求信息
    sysLog.setIp(ip);

    //设置调用的类
    sysLog.setClassPath(classPath);

    //设置调用的方法
    sysLog.setMethod(methodName);

    //设置Request的请求方式 GET POST
    sysLog.setType(request.getMethod());

    sysLog.setUrl(request.getRequestURI());

    sysLog.setOperation(operationName);
    sysLog.setCreateTime(new Date());
    sysLog.setUpdateTime(new Date());
    SecurityUser securityUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    sysLog.setUserName(securityUser.getUsername());
    sysLog.setAdminUid(securityUser.getUid());
    sysLog.setParams(paramsJson);

    Date endTime = new Date();
    Long spendTime = DateUtil.between(startTime, endTime, DateUnit.MS);

    // 计算请求接口花费的时间,单位毫秒
    sysLog.setSpendTime(spendTime);

    sysLog.insert();
}
 
Example 12
Source File: AdminController.java    From mayday with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 验证
 * 
 * @param userName
 *            用户名
 * @param userPwd
 *            用户密码
 * @param session
 * @return
 */
@PostMapping(value = "getLogin")
@ResponseBody
public JsonResult getLogin(@RequestParam(value = "userName") String userName,
		@RequestParam(value = "userPwd") String userPwd, HttpSession session) {
	try {
		// 禁止时间10分钟
		int inhibitTime = 10;
		// 为true禁止登录
		String flag = "true";
		// 错误总次数5次
		int errorCount = 5;
		// 已注册用户
		User users = userService.findUser();
		// 判断账户是否被禁用十分钟
		Date date = DateUtil.date();
		if (users.getLoginLastTime() != null) {
			date = users.getLoginLastTime();
		}
		// 计算两个日期之间的时间差
		long between = DateUtil.between(date, DateUtil.date(), DateUnit.MINUTE);
		if (StrUtil.equals(users.getLoginEnable(), flag) && (between < inhibitTime)) {
			return new JsonResult(false, "账户被禁止登录10分钟,请稍后重试");
		}
		// 验证用户名密码
		User user = userService.getByNameAndPwd(userName, SecureUtil.md5(userPwd));
		// 修改最后登录时间
		userService.updateLoginLastTime(DateUtil.date(), users.getUserId());
		if (user != null) {
			session.setAttribute(MaydayConst.USER_SESSION_KEY, user);
			// 登录成功重置用户状态为正常
			userService.updateUserNormal(user.getUserId());
			// 添加登录日志
			logService.save(new Log(LogConstant.LOGIN, LogConstant.LOGIN_SUCCES, ServletUtil.getClientIP(request),
					DateUtil.date()));
			log.info(userName + "登录成功");
			return new JsonResult(true, "登录成功");
		} else {
			Integer error = userService.updateError();
			if (error == errorCount) {
				userService.updateLoginEnable("true",0);
			}else if(error==1) {
				userService.updateLoginEnable("false",1);
			}
			// 添加失败日志
			logService.save(new Log(LogConstant.LOGIN, LogConstant.LOGIN_ERROR, ServletUtil.getClientIP(request),
					DateUtil.date()));
			return new JsonResult(false, "用户名或密码错误!你还有" + (5 - error) + "次机会");
		}
	} catch (Exception e) {
		log.error("登录失败,系统错误!",e);
		return new JsonResult(false, "未知错误!");
	}
}
 
Example 13
Source File: AdminController.java    From blog-sharon with Apache License 2.0 4 votes vote down vote up
/**
 * 验证登录信息
 *
 * @param loginName 登录名:邮箱/用户名
 * @param loginPwd  loginPwd 密码
 * @param session   session session
 * @return JsonResult JsonResult
 */
@PostMapping(value = "/getLogin")
@ResponseBody
public JsonResult getLogin(@ModelAttribute("loginName") String loginName,
                           @ModelAttribute("loginPwd") String loginPwd,
                           HttpSession session) {
    //已注册账号,单用户,只有一个
    User aUser = userService.findUser();
    //首先判断是否已经被禁用已经是否已经过了10分钟
    Date loginLast = DateUtil.date();
    if (null != aUser.getLoginLast()) {
        loginLast = aUser.getLoginLast();
    }
    Long between = DateUtil.between(loginLast, DateUtil.date(), DateUnit.MINUTE);
    if (StrUtil.equals(aUser.getLoginEnable(), TrueFalseEnum.FALSE.getDesc()) && (between < CommonParamsEnum.TEN.getValue())) {
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.disabled"));
    }
    //验证用户名和密码
    User user = null;
    if (Validator.isEmail(loginName)) {
        user = userService.userLoginByEmail(loginName, SecureUtil.md5(loginPwd));
    } else {
        user = userService.userLoginByName(loginName, SecureUtil.md5(loginPwd));
    }
    userService.updateUserLoginLast(DateUtil.date());
    //判断User对象是否相等
    if (ObjectUtil.equal(aUser, user)) {
        session.setAttribute(HaloConst.USER_SESSION_KEY, aUser);
        //重置用户的登录状态为正常
        userService.updateUserNormal();
        logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_SUCCESS, request);
        log.info("User {} login succeeded.", aUser.getUserDisplayName());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.login.success"));
    } else {
        //更新失败次数
        Integer errorCount = userService.updateUserLoginError();
        //超过五次禁用账户
        if (errorCount >= CommonParamsEnum.FIVE.getValue()) {
            userService.updateUserLoginEnable(TrueFalseEnum.FALSE.getDesc());
        }
        logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_ERROR + "[" + HtmlUtil.escape(loginName) + "," + HtmlUtil.escape(loginPwd) + "]", request);
        Object[] args = {(5 - errorCount)};
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.failed", args));
    }
}