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

The following examples show how to use cn.hutool.core.date.DateUtil#date() . 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: TopManager.java    From Jpom with MIT License 5 votes vote down vote up
public static Iterator<CacheObj<String, JSONObject>> get() {
    JSONObject topInfo = AbstractSystemCommander.getInstance().getAllMonitor();
    if (topInfo != null) {
        DateTime date = DateUtil.date();
        String time = DateUtil.formatTime(date);
        topInfo.put("time", time);
        topInfo.put("monitorTime", date.getTime());
        MONITOR_CACHE.put(time, topInfo);
    }
    return MONITOR_CACHE.cacheObjIterator();
}
 
Example 2
Source File: FwTradeLog.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
public FwTradeLog(StatusEnum status) {
    this.createTime = DateUtil.date();
    this.status = status.getValue();
    this.statusDsc=status.getDesc();
    this.orderAmount=new BigDecimal("100.00");
    this.userId=RandomUtil.randomLong(1000000);
    this.orderId= RandomUtil.randomLong(1000000);
}
 
Example 3
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 4
Source File: ArticleRepositoryTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 测试新增
 */
@Test
public void testSave() {
    Article article = new Article(1L, RandomUtil.randomString(20), RandomUtil.randomString(150), DateUtil.date(), DateUtil
            .date(), 0L, 0L);
    articleRepo.save(article);
    log.info("【article】= {}", JSONUtil.toJsonStr(article));
}
 
Example 5
Source File: OrderUtil.java    From supplierShop with MIT License 4 votes vote down vote up
/**
 * 时间戳订单号
 * @return
 */
public static String orderSn(){
    Date date = DateUtil.date();
    return DateUtil.format(date,"yyyyMMddHHmmssSSS");
}
 
Example 6
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 7
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 8
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 9
Source File: AttachmentController.java    From mayday with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 上传功能
 * 
 * @param file
 * @param request
 * @return
 */
public JsonResult uploadAttachment(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
	if (!file.isEmpty()) {
		try {
			// 获取用户目录
			String userPath = System.getProperties().getProperty("user.home") + "/mayday/";
			// 保存目录
			StringBuffer hold = new StringBuffer("upload/");
			// 获取时间,以年月创建目录
			Date date = DateUtil.date();
			hold.append(DateUtil.thisYear()).append("/").append(DateUtil.thisMonth() + 1).append("/");
			File mediaPath = new File(userPath, hold.toString());
			// 如果没有该目录则创建
			if (!mediaPath.exists()) {
				mediaPath.mkdirs();
			}
			System.out.println("路径++++++" + mediaPath);
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			// 生成文件名称
			String nameSuffix = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."))
					.replaceAll(" ", "_").replaceAll(",", "") + format.format(DateUtil.date())
					+ new Random().nextInt(1000);
			// 文件后缀
			String fileSuffix = file.getOriginalFilename()
					.substring(file.getOriginalFilename().lastIndexOf(".") + 1);
			// 上传文件名加后缀
			String fileName = nameSuffix + "." + fileSuffix;

			// 转存文件
			file.transferTo(new File(mediaPath.toString(), fileName));

			// 原图片路径
			StringBuffer originalPath = new StringBuffer();
			originalPath.append(mediaPath.getAbsolutePath()).append("/").append(fileName);
			// 压缩图片路径
			StringBuffer compressPath = new StringBuffer();
			compressPath.append(mediaPath.getAbsolutePath()).append("/").append(nameSuffix).append("_small.")
					.append(fileSuffix);
			// 压缩图片
			Thumbnails.of(originalPath.toString()).size(256, 256).keepAspectRatio(false).toFile(compressPath.toString());
			// 原图数据库路径
			StringBuffer originalDataPath = new StringBuffer();
			originalDataPath.append("/").append(hold).append(fileName);
			// 压缩图数据库路径
			StringBuffer compressDataPath = new StringBuffer();
			compressDataPath.append("/").append(hold).append(nameSuffix).append("_small.").append(fileSuffix);
			// 添加数据库
			Attachment attachment = new Attachment();
			attachment.setPictureName(fileName);
			attachment.setPicturePath(originalDataPath.toString());
			attachment.setPictureType(file.getContentType());
			attachment.setPictureCreateDate(date);
			attachment.setPictureSuffix(new StringBuffer().append(".").append(fileSuffix).toString());
			attachment.setPictureSmallPath(compressDataPath.toString());
			attachment.setPictureWh(MaydayUtil.getImageWh(new File(mediaPath.toString() + "/" + fileName)));
			attachment.setPictureSize(MaydayUtil.parseSize(new File(mediaPath.toString() + "/" + fileName).length()));
			attachmentService.save(attachment);
			// 添加日志
			logService.save(new Log(LogConstant.UPLOAD_ATTACHMENT, LogConstant.UPLOAD_SUCCESS,
					ServletUtil.getClientIP(request), DateUtil.date()));
		} catch (Exception e) {
			log.error("上传附件错误" + e.getMessage());
			return new JsonResult(false, "系统未知错误");
		}
	} else {
		return new JsonResult(false, "文件不能为空");
	}
	return new JsonResult(true, "上传成功");
}
 
Example 10
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));
    }
}
 
Example 11
Source File: OrderUtil.java    From yshopmall with Apache License 2.0 2 votes vote down vote up
/**
 * 时间戳订单号
 *
 * @return
 */
public static String orderSn() {
    Date date = DateUtil.date();
    return DateUtil.format(date, "yyyyMMddHHmmssSSS");
}