新增部分内容

This commit is contained in:
wenc000 2019-08-17 08:56:38 +08:00
parent 99441e06be
commit c4dfc7ea85
16 changed files with 610 additions and 514 deletions

View File

@ -29,4 +29,9 @@ public interface IApiConsts {
*/
String LIST_USER_BY_ID = "%s/resource/user/listuserbyids";
/**
* 全部用户
*/
String LIST_ALL_USER = "%s/resource/user/listalluser";
}

View File

@ -3,6 +3,7 @@ package com.cm.common.plugin.oauth.controller.apis.department;
import com.alibaba.fastjson.JSONArray;
import com.cm.common.base.AbstractController;
import com.cm.common.constants.ISystemConstant;
import com.cm.common.exception.AccessTokenException;
import com.cm.common.exception.SearchException;
import com.cm.common.plugin.oauth.service.department.IDepartmentService;
import org.apache.commons.lang3.StringUtils;
@ -33,7 +34,7 @@ public class DepartmentController extends AbstractController {
private IDepartmentService departmentService;
@GetMapping("listdepartments")
public JSONArray listDepartments() throws SearchException {
public JSONArray listDepartments() throws SearchException, AccessTokenException {
Map<String, Object> params = requestParams();
String parentId = "0";
if (!StringUtils.isBlank(params.get("id") == null ? null : params.get("id").toString())) {

View File

@ -3,6 +3,7 @@ package com.cm.common.plugin.oauth.controller.apis.menu;
import com.alibaba.fastjson.JSONArray;
import com.cm.common.base.AbstractController;
import com.cm.common.constants.ISystemConstant;
import com.cm.common.exception.AccessTokenException;
import com.cm.common.exception.SearchException;
import com.cm.common.plugin.oauth.service.menu.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
@ -27,7 +28,7 @@ public class MenuController extends AbstractController {
private IMenuService menuService;
@GetMapping("listmenu")
public JSONArray listMenu() throws SearchException {
public JSONArray listMenu() throws AccessTokenException {
Map<String, Object> params = requestParams();
return menuService.listMenu(params);
}

View File

@ -3,6 +3,7 @@ package com.cm.common.plugin.oauth.controller.apis.user;
import com.alibaba.fastjson.JSONArray;
import com.cm.common.base.AbstractController;
import com.cm.common.constants.ISystemConstant;
import com.cm.common.exception.AccessTokenException;
import com.cm.common.exception.SearchException;
import com.cm.common.plugin.oauth.service.user.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
@ -35,7 +36,7 @@ public class UserController extends AbstractController {
* @throws SearchException
*/
@GetMapping("listdepartmentusers/{departmentId}")
public JSONArray listDepartmentUsers(@PathVariable("departmentId") String departmentId) throws SearchException {
public JSONArray listDepartmentUsers(@PathVariable("departmentId") String departmentId) throws AccessTokenException {
Map<String, Object> params = getParams();
params.put("departmentId", departmentId);
return userService.listDepartmentUsers(params);
@ -46,13 +47,24 @@ public class UserController extends AbstractController {
*
* @param userIds
* @return
* @throws SearchException
* @throws AccessTokenException
*/
@GetMapping("listuserbyids/{userIds}")
public JSONArray listUserByIds(@PathVariable("userIds") String userIds) throws SearchException {
public JSONArray listUserByIds(@PathVariable("userIds") String userIds) throws AccessTokenException {
Map<String, Object> params = getParams();
params.put("userIds", userIds);
return userService.listUserByIds(params);
}
/**
* 全部用户
*
* @return
*/
@GetMapping("listallusers")
public JSONArray listAllUsers() throws AccessTokenException {
Map<String, Object> params = getParams();
return userService.listAllUsers(params);
}
}

View File

@ -1,6 +1,7 @@
package com.cm.common.plugin.oauth.service.department;
import com.alibaba.fastjson.JSONArray;
import com.cm.common.exception.AccessTokenException;
import com.cm.common.exception.SearchException;
import java.util.Map;
@ -24,6 +25,6 @@ public interface IDepartmentService {
* @return
* @throws SearchException
*/
JSONArray listDepartments(Map<String, Object> params) throws SearchException;
JSONArray listDepartments(Map<String, Object> params) throws AccessTokenException, AccessTokenException;
}

View File

@ -3,6 +3,7 @@ package com.cm.common.plugin.oauth.service.department.impl;
import com.alibaba.fastjson.JSONArray;
import com.cm.common.base.AbstractService;
import com.cm.common.config.properties.ApiPathProperties;
import com.cm.common.exception.AccessTokenException;
import com.cm.common.exception.SearchException;
import com.cm.common.plugin.IApiConsts;
import com.cm.common.plugin.oauth.service.department.IDepartmentService;
@ -32,10 +33,10 @@ public class DepartmentServiceImpl extends AbstractService implements IDepartmen
private ApiPathProperties apiPathProperties;
@Override
public JSONArray listDepartments(Map<String, Object> params) throws SearchException {
public JSONArray listDepartments(Map<String, Object> params) throws AccessTokenException {
String result = restTemplateUtil.doPostForm(String.format(IApiConsts.LIST_DEPARTMENT, apiPathProperties.getUserCenter(), params.get("parentId").toString()), params);
if (StringUtils.isBlank(result)) {
throw new SearchException("获取组织部门列表失败");
throw new AccessTokenException("获取组织部门列表失败");
}
return JSONArray.parseArray(result);
}

View File

@ -1,6 +1,7 @@
package com.cm.common.plugin.oauth.service.menu;
import com.alibaba.fastjson.JSONArray;
import com.cm.common.exception.AccessTokenException;
import com.cm.common.exception.SearchException;
import java.util.Map;
@ -21,6 +22,6 @@ public interface IMenuService {
* @param params
* @return
*/
JSONArray listMenu(Map<String, Object> params) throws SearchException;
JSONArray listMenu(Map<String, Object> params) throws AccessTokenException, AccessTokenException;
}

View File

@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cm.common.base.AbstractService;
import com.cm.common.config.properties.ApiPathProperties;
import com.cm.common.exception.AccessTokenException;
import com.cm.common.exception.SearchException;
import com.cm.common.plugin.IApiConsts;
import com.cm.common.plugin.oauth.service.menu.IMenuService;
@ -33,10 +34,10 @@ public class MenuServiceImpl extends AbstractService implements IMenuService {
private ApiPathProperties apiPathProperties;
@Override
public JSONArray listMenu(Map<String, Object> params) throws SearchException {
public JSONArray listMenu(Map<String, Object> params) throws AccessTokenException {
String result = restTemplateUtil.doPostForm(String.format(IApiConsts.LIST_MENU, apiPathProperties.getUserCenter(), oAuth2ClientProperties.getClientId()), params);
if (StringUtils.isBlank(result)) {
throw new SearchException("获取列表失败");
throw new AccessTokenException("获取列表失败");
}
JSONObject resultObj = JSONObject.parseObject(result);
return resultObj.getJSONArray("data");

View File

@ -1,6 +1,7 @@
package com.cm.common.plugin.oauth.service.user;
import com.alibaba.fastjson.JSONArray;
import com.cm.common.exception.AccessTokenException;
import com.cm.common.exception.SearchException;
import java.util.Map;
@ -23,7 +24,7 @@ public interface IUserService {
* @return
* @throws SearchException
*/
JSONArray listDepartmentUsers(Map<String, Object> params) throws SearchException;
JSONArray listDepartmentUsers(Map<String, Object> params) throws AccessTokenException;
/**
* 通过id列表获取用户ID
@ -32,5 +33,14 @@ public interface IUserService {
* @return
* @throws SearchException
*/
JSONArray listUserByIds(Map<String, Object> params) throws SearchException;
JSONArray listUserByIds(Map<String, Object> params) throws AccessTokenException;
/**
* 全部用户
*
* @param params
* @return
* @throws SearchException
*/
JSONArray listAllUsers(Map<String, Object> params) throws AccessTokenException;
}

View File

@ -3,7 +3,9 @@ package com.cm.common.plugin.oauth.service.user.impl;
import com.alibaba.fastjson.JSONArray;
import com.cm.common.base.AbstractService;
import com.cm.common.config.properties.ApiPathProperties;
import com.cm.common.exception.AccessTokenException;
import com.cm.common.exception.SearchException;
import com.cm.common.exception.TokenException;
import com.cm.common.plugin.IApiConsts;
import com.cm.common.plugin.oauth.service.user.IUserService;
import com.cm.common.plugin.utils.RestTemplateUtil;
@ -32,19 +34,28 @@ public class UserServiceImpl extends AbstractService implements IUserService {
private ApiPathProperties apiPathProperties;
@Override
public JSONArray listDepartmentUsers(Map<String, Object> params) throws SearchException {
public JSONArray listDepartmentUsers(Map<String, Object> params) throws AccessTokenException {
String result = restTemplateUtil.doPostForm(String.format(IApiConsts.LIST_DEPARTMENT_USER, apiPathProperties.getUserCenter(), params.get("departmentId").toString()), params);
if (StringUtils.isBlank(result)) {
throw new SearchException("获取人员列表失败");
throw new AccessTokenException("获取人员列表失败");
}
return JSONArray.parseArray(result);
}
@Override
public JSONArray listUserByIds(Map<String, Object> params) throws SearchException {
public JSONArray listUserByIds(Map<String, Object> params) throws AccessTokenException {
String result = restTemplateUtil.doPostForm(String.format(IApiConsts.LIST_USER_BY_ID, apiPathProperties.getUserCenter()), params);
if (StringUtils.isBlank(result)) {
throw new SearchException("获取人员列表失败");
throw new AccessTokenException("获取人员列表失败");
}
return JSONArray.parseArray(result);
}
@Override
public JSONArray listAllUsers(Map<String, Object> params) throws AccessTokenException {
String result = restTemplateUtil.doPostForm(String.format(IApiConsts.LIST_ALL_USER, apiPathProperties.getUserCenter()), params);
if (StringUtils.isBlank(result)) {
throw new AccessTokenException("获取全部人员列表失败");
}
return JSONArray.parseArray(result);
}

View File

@ -6,7 +6,9 @@ import com.cm.common.constants.ISystemConstant;
import com.cm.common.enums.UploadTypeEnum;
import com.cm.common.exception.base.SystemException;
import com.cm.common.plugin.service.file.IFileService;
import com.cm.common.result.ErrorResult;
import com.cm.common.result.SuccessResultData;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@ -25,6 +27,7 @@ import java.util.Map;
* @Date: 2019/3/10 7:03 PM
* @Version: 1.0
**/
@Api(tags = ISystemConstant.API_TAGS_SYSTEM_PREFIX + "文件管理接口")
@RestController
@RequestMapping(ISystemConstant.API_PREFIX + "/file")
public class FileController extends AbstractController {
@ -32,49 +35,44 @@ public class FileController extends AbstractController {
@Autowired
private IFileService fileService;
/**
* 上传文件
*
* @param file
* @return
*/
@ApiOperation(value = "上传文件", notes = "上传文件接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "file", value = "文件name", paramType = "form")
})
@ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
@PostMapping("uploadfile")
public SuccessResultData<String> uploadFile(@RequestParam("file") MultipartFile file) throws SystemException {
Map<String, Object> params = requestParams();
return uploadSingle(file, UploadTypeEnum.FILE, params);
}
/**
* 上传图片
*
* @param image
* @return
*/
@ApiOperation(value = "上传图片", notes = "上传图片接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "image", value = "文件name", paramType = "form")
})
@ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
@PostMapping("uploadimage")
public SuccessResultData<String> uploadImage(@RequestParam("image") MultipartFile image) throws SystemException {
Map<String, Object> params = requestParams();
return uploadSingle(image, UploadTypeEnum.IMAGE, params);
}
/**
* 上传视频
*
* @param video
* @return
*/
@ApiOperation(value = "上传视频", notes = "上传视频接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "video", value = "文件video", paramType = "form")
})
@ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
@PostMapping("uploadvideo")
public SuccessResultData<String> uploadVideo(@RequestParam("video") MultipartFile video) throws SystemException {
Map<String, Object> params = requestParams();
return uploadSingle(video, UploadTypeEnum.VIDEO, params);
}
/**
* 上传音频
*
* @param audio
* @return
* @throws SystemException
*/
@ApiOperation(value = "上传音频", notes = "上传音频接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "audio", value = "文件audio", paramType = "form")
})
@ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
@PostMapping("uploadaudio")
public SuccessResultData<String> uploadAudio(@RequestParam("audio") MultipartFile audio) throws SystemException {
Map<String, Object> params = requestParams();

View File

@ -5,7 +5,9 @@ import com.cm.common.constants.ISystemConstant;
import com.cm.common.enums.UploadTypeEnum;
import com.cm.common.exception.base.SystemException;
import com.cm.common.plugin.service.file.IFileService;
import com.cm.common.result.ErrorResult;
import com.cm.common.result.SuccessResultData;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@ -22,6 +24,7 @@ import java.util.Map;
* @Date: 2019-08-02 15:38
* @Version: 1.0
**/
@Api(tags = ISystemConstant.API_TAGS_APP_PREFIX + "文件管理接口")
@RestController
@RequestMapping(ISystemConstant.APP_PREFIX + "/file")
public class FileAppController extends AbstractController {
@ -29,49 +32,48 @@ public class FileAppController extends AbstractController {
@Autowired
private IFileService fileService;
/**
* 上传文件
*
* @param file
* @return
*/
@ApiOperation(value = "上传文件", notes = "上传文件接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "token", value = "token", paramType = "header"),
@ApiImplicitParam(name = "file", value = "文件name", paramType = "form")
})
@ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
@PostMapping("uploadfile")
public SuccessResultData<String> uploadFile(@RequestHeader("token") String token, @RequestParam("file") MultipartFile file) throws SystemException {
Map<String, Object> params = requestParams();
return uploadSingle(token, file, UploadTypeEnum.FILE, params);
}
/**
* 上传图片
*
* @param image
* @return
*/
@ApiOperation(value = "上传图片", notes = "上传图片接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "token", value = "token", paramType = "header"),
@ApiImplicitParam(name = "image", value = "文件name", paramType = "form")
})
@ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
@PostMapping("uploadimage")
public SuccessResultData<String> uploadImage(@RequestHeader("token") String token, @RequestParam("image") MultipartFile image) throws SystemException {
Map<String, Object> params = requestParams();
return uploadSingle(token, image, UploadTypeEnum.IMAGE, params);
}
/**
* 上传视频
*
* @param video
* @return
*/
@ApiOperation(value = "上传视频", notes = "上传视频接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "token", value = "token", paramType = "header"),
@ApiImplicitParam(name = "video", value = "文件video", paramType = "form")
})
@ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
@PostMapping("uploadvideo")
public SuccessResultData<String> uploadVideo(@RequestHeader("token") String token, @RequestParam("video") MultipartFile video) throws SystemException {
Map<String, Object> params = requestParams();
return uploadSingle(token, video, UploadTypeEnum.VIDEO, params);
}
/**
* 上传音频
*
* @param audio
* @return
* @throws SystemException
*/
@ApiOperation(value = "上传音频", notes = "上传音频接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "token", value = "token", paramType = "header"),
@ApiImplicitParam(name = "audio", value = "文件audio", paramType = "form")
})
@ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
@PostMapping("uploadaudio")
public SuccessResultData<String> uploadAudio(@RequestHeader("token") String token, @RequestParam("audio") MultipartFile audio) throws SystemException {
Map<String, Object> params = requestParams();

View File

@ -6,6 +6,8 @@ import com.cm.common.constants.ISystemConstant;
import com.cm.common.exception.ParamsException;
import com.cm.common.exception.SearchException;
import com.cm.common.plugin.service.file.IFileService;
import com.cm.common.result.ErrorResult;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@ -24,6 +26,7 @@ import java.util.Map;
* @Date: 2019/3/11 2:45 PM
* @Version: 1.0
**/
@Api(tags = ISystemConstant.API_TAGS_SYSTEM_PREFIX + "文件管理接口")
@Controller
@RequestMapping(ISystemConstant.ROUTE_PREFIX + "/file")
public class FileRouteController extends AbstractController {
@ -33,12 +36,12 @@ public class FileRouteController extends AbstractController {
@Autowired
private FileProperties fileProperties;
/**
* 打开文件上传
*
* @param uploadType
* @return
*/
@ApiOperation(value = "打开文件上传", notes = "打开文件上传接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "uploadType", value = "文件类型,1:文件,2:图片,3:视频,4:音频", paramType = "path")
})
@ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
@GetMapping("uploadfile/{uploadType}")
public ModelAndView uploadFile(@PathVariable("uploadType") String uploadType) throws ParamsException {
ModelAndView mv = new ModelAndView("file/file-upload");
@ -90,14 +93,12 @@ public class FileRouteController extends AbstractController {
return mv;
}
/**
* 下载文件
*
* @param response
* @param isOpen
* @param fileId
* @return
*/
@ApiOperation(value = "下载文件", notes = "下载文件接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "isOpen", value = "是否打开,true和false", paramType = "path"),
@ApiImplicitParam(name = "fileId", value = "文件ID", paramType = "path")
})
@ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
@GetMapping("downloadfile/{isOpen}/{fileId}")
public void downLoadFile(HttpServletResponse response, @PathVariable("isOpen") String isOpen, @PathVariable("fileId") String fileId) throws ParamsException, SearchException {
if (!ISystemConstant.IS_TRUE.equals(isOpen) && !ISystemConstant.IS_FALSE.equals(isOpen)) {

View File

@ -48,6 +48,8 @@ public class ResponseAdvice {
result.setCode(ErrorResultCodeEnum.PARAMS_ERROR.getValue());
} else if (e instanceof FileException) {
result.setCode(ErrorResultCodeEnum.FILE_ERROR.getValue());
} else if(e instanceof AccessTokenException) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
}
// 自定义提示信息
if (e instanceof SystemException) {

View File

@ -0,0 +1,34 @@
package com.cm.common.exception;
import com.cm.common.exception.base.SystemException;
/**
* When you feel like quitting. Think about why you started
* 当你想要放弃的时候想想当初你为何开始
*
* @ClassName: AccessTokenException
* @Description: accessToken异常
* @Author: WangGeng
* @Date: 2019-08-15 18:00
* @Version: 1.0
**/
public class AccessTokenException extends SystemException {
public AccessTokenException() {
}
public AccessTokenException(String message) {
super(message);
}
public AccessTokenException(String message, boolean withMsg) {
super(message, withMsg);
}
public AccessTokenException(String message, Throwable cause) {
super(message, cause);
}
public AccessTokenException(Throwable cause) {
super(cause);
}
}

View File

@ -1,433 +1,448 @@
package com.cm.common.utils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* 说明日期处理 创建人CM 修改时间2015年11月24日
*/
public class DateUtil {
private final static SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
private final static SimpleDateFormat sdfMonth = new SimpleDateFormat("MM");
private final static SimpleDateFormat sdfd = new SimpleDateFormat("dd");
private final static SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");
private final static SimpleDateFormat sdfDayZh = new SimpleDateFormat("yyyy年MM月dd日");
private final static SimpleDateFormat sdfDays = new SimpleDateFormat("yyyyMMdd");
private final static SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private final static SimpleDateFormat sdfTimes = new SimpleDateFormat("yyyyMMddHHmmss");
private final static SimpleDateFormat sdfYearMonth = new SimpleDateFormat("yyyyMM");
public static String getZhDate(String date) {
try {
return sdfDayZh.format(sdfDay.parse(date));
} catch (Exception e) {
e.printStackTrace();
return date;
}
}
/**
* 校验日期格式
*
* @param date
* @param simpleDateFormat
* @return
*/
public static boolean checkFormat(String date, SimpleDateFormat simpleDateFormat) {
if (StringUtils.isEmpty(date) || simpleDateFormat == null) {
return false;
}
try {
simpleDateFormat.parse(date);
return true;
} catch (ParseException e) {
return false;
}
}
/**
* 获取YYYYMM格式
*
* @return
*/
public static String getSdfYearMonth() {
return sdfYearMonth.format(new Date());
}
/**
* 获取YYYYMMDDHHMMSS格式
*
* @return
*/
public static String getSdfTimes() {
return sdfTimes.format(new Date());
}
/**
* 获取YYYY格式
*
* @return
*/
public static String getYear() {
return sdfYear.format(new Date());
}
/**
* 获取MM格式
*
* @return
*/
public static String getMonth() {
return sdfMonth.format(new Date());
}
/**
* 获取dd格式
*
* @return
*/
public static String getToday() {
return sdfd.format(new Date());
}
/**
* 获取YYYY-MM-DD格式
*
* @return
*/
public static String getDay() {
return sdfDay.format(new Date());
}
/**
* 获取YYYYMMDD格式
*
* @return
*/
public static String getDays() {
return sdfDays.format(new Date());
}
/**
* 获取YYYY-MM-DD HH:mm:ss格式
*
* @return
*/
public static String getTime() {
return sdfTime.format(new Date());
}
/**
* 截取日期
*
* @param datetime
* @return
*/
public static String getDate(String datetime) {
return datetime.substring(0, 10);
}
/**
* @param s
* @param e
* @return boolean
* @throws @author fh
* @Title: compareDate
* @Description: TODO(日期比较 如果s > = e 返回true 否则返回false)
*/
public static boolean compareDate(String s, String e) {
if (fomatDate(s) == null || fomatDate(e) == null) {
return false;
}
return fomatDate(s).getTime() >= fomatDate(e).getTime();
}
/**
* 格式化日期
*
* @param date
* @return
*/
public static Date fomatDate(String date) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
return fmt.parse(date);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 校验日期是否合法
*
* @param s
* @return
*/
public static boolean isValidDate(String s) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
fmt.parse(s);
return true;
} catch (Exception e) {
// 如果throw java.text.ParseException或者NullPointerException就说明格式不对
return false;
}
}
/**
* @param startTime
* @param endTime
* @return
*/
public static int getDiffYear(String startTime, String endTime) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
// long aa=0;
int years = (int) (((fmt.parse(endTime).getTime() - fmt.parse(startTime).getTime()) / (1000 * 60 * 60 * 24))
/ 365);
return years;
} catch (Exception e) {
// 如果throw java.text.ParseException或者NullPointerException就说明格式不对
return 0;
}
}
/**
* <li>功能描述时间相减得到天数
*
* @param beginDateStr
* @param endDateStr
* @return long
* @author Administrator
*/
public static long getDaySub(String beginDateStr, String endDateStr) {
long day = 0;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate = null;
Date endDate = null;
try {
beginDate = format.parse(beginDateStr);
endDate = format.parse(endDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
// System.out.println("相隔的天数="+day);
return day;
}
/**
* 得到n天之后的日期
*
* @param days
* @return
*/
public static String getAfterDayDate(String days) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdfd.format(date);
return dateStr;
}
/**
* 得到n天之后是周几
*
* @param days
* @return
*/
public static String getAfterDayWeek(String days) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("E");
String dateStr = sdf.format(date);
return dateStr;
}
/**
* 计算年龄生日格式yyyy-MM-dd
*
* @param birth
* @return
*/
public static String getAge(String birth) {
int cYear = Integer.parseInt(getYear());
String[] births = birth.split("-");
int year = Integer.parseInt(births[0]);
if (cYear <= year) {
return "0";
}
int cMonth = Integer.parseInt(getMonth());
int cDay = Integer.parseInt(getToday());
int month = Integer.parseInt(births[1]);
int day = Integer.parseInt(births[2]);
int age = cYear - year;
if (cMonth - month > 0) {
return String.valueOf(age);
}
if (cDay - day > 0) {
return String.valueOf(age);
}
return String.valueOf(age - 1);
}
/**
* 获取本周周一的日期
*/
public static String weekStartDate(String pattern) {
return new DateTime().dayOfWeek().withMinimumValue().toString(pattern);
}
/**
* 获取本周周一的日期
*/
public static Date weekStartDate() {
return new DateTime().dayOfWeek().withMinimumValue().toDate();
}
/**
* 获取本周最后一天
*
* @return
*/
public static String weekEndDate(String pattern) {
return new DateTime().dayOfWeek().withMaximumValue().toString(pattern);
}
/**
* 获取本周最后一天
*
* @return
*/
public static Date weekEndDate() {
return new DateTime().dayOfWeek().withMaximumValue().toDate();
}
/**
* 获取本月开始日期
*
* @param pattern
* @return
*/
public static String monthStartDate(String pattern) {
return new DateTime().dayOfMonth().withMinimumValue().toString(pattern);
}
/**
* 获取本月开始日期
*
* @param pattern
* @return
*/
public static Date monthStartDate() {
return new DateTime().dayOfMonth().withMinimumValue().toDate();
}
/**
* 获取本月结束日期
*
* @param pattern
* @return
*/
public static String monthEndDate(String pattern) {
return new DateTime().dayOfMonth().withMaximumValue().toString(pattern);
}
/**
* 获取本月结束日期
*
* @param pattern
* @return
*/
public static Date monthEndDate() {
return new DateTime().dayOfMonth().withMaximumValue().toDate();
}
/**
* 格式化日期
*
* @param parseLong
* @param format
* @return
*/
public static String formatDate(long parseLong, String format) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormat.format(new Date(parseLong));
}
/**
* 获取前几天的日期带格式
*
* @param day
* @param format
* @return
*/
public static String getBeforeDate(int day, String format) {
DateTime time = new DateTime().plusDays(-day);
return sdfDay.format(time.toDate());
}
/**
* 计算时间差
*
* @param startTime
* @param endTime
* @param format
* @return
*/
public static long getTimeConsuming(String startTime, String endTime, String format) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
long start = simpleDateFormat.parse(startTime).getTime();
long end = simpleDateFormat.parse(endTime).getTime();
long useTime = end - start;
return useTime < 0 ? 0 : useTime;
}
/**
* 计算年龄
*
* @param birthday yyyy-MM-dd
* @return
*/
public static int getAgeByBirthday(String birthday) {
int age = 0;
String[] days = getDay().split("-");
String[] births = birthday.split("-");
int year = Integer.parseInt(days[0]);
int birthYear = Integer.parseInt(births[0]);
int month = Integer.parseInt(days[1]);
int birthMonth = Integer.parseInt(births[1]);
int day = Integer.parseInt(days[2]);
int birthDay = Integer.parseInt(births[2]);
// 判断年龄是否相等
if (year - birthYear > 0) {
if (month - birthMonth > 0) {
return year - birthYear;
} else if (month - birthMonth == 0) {
if (day - birthDay > 0) {
return year - birthYear;
}
return year - birthYear - 1;
}
return year - birthYear - 1;
}
return age;
}
}
package com.cm.common.utils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* 说明日期处理 创建人CM 修改时间2015年11月24日
*/
public class DateUtil {
public final static String AM = "AM";
public final static String PM = "PM";
private final static SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
private final static SimpleDateFormat sdfMonth = new SimpleDateFormat("MM");
private final static SimpleDateFormat sdfd = new SimpleDateFormat("dd");
private final static SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");
private final static SimpleDateFormat sdfDayZh = new SimpleDateFormat("yyyy年MM月dd日");
private final static SimpleDateFormat sdfDays = new SimpleDateFormat("yyyyMMdd");
private final static SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private final static SimpleDateFormat sdfTimes = new SimpleDateFormat("yyyyMMddHHmmss");
private final static SimpleDateFormat sdfYearMonth = new SimpleDateFormat("yyyyMM");
public static String getZhDate(String date) {
try {
return sdfDayZh.format(sdfDay.parse(date));
} catch (Exception e) {
e.printStackTrace();
return date;
}
}
/**
* 校验日期格式
*
* @param date
* @param simpleDateFormat
* @return
*/
public static boolean checkFormat(String date, SimpleDateFormat simpleDateFormat) {
if (StringUtils.isEmpty(date) || simpleDateFormat == null) {
return false;
}
try {
simpleDateFormat.parse(date);
return true;
} catch (ParseException e) {
return false;
}
}
/**
* 获取YYYYMM格式
*
* @return
*/
public static String getSdfYearMonth() {
return sdfYearMonth.format(new Date());
}
/**
* 获取YYYYMMDDHHMMSS格式
*
* @return
*/
public static String getSdfTimes() {
return sdfTimes.format(new Date());
}
/**
* 获取YYYY格式
*
* @return
*/
public static String getYear() {
return sdfYear.format(new Date());
}
/**
* 获取MM格式
*
* @return
*/
public static String getMonth() {
return sdfMonth.format(new Date());
}
/**
* 获取dd格式
*
* @return
*/
public static String getToday() {
return sdfd.format(new Date());
}
/**
* 获取YYYY-MM-DD格式
*
* @return
*/
public static String getDay() {
return sdfDay.format(new Date());
}
/**
* 获取YYYYMMDD格式
*
* @return
*/
public static String getDays() {
return sdfDays.format(new Date());
}
/**
* 获取YYYY-MM-DD HH:mm:ss格式
*
* @return
*/
public static String getTime() {
return sdfTime.format(new Date());
}
/**
* 截取日期
*
* @param datetime
* @return
*/
public static String getDate(String datetime) {
return datetime.substring(0, 10);
}
/**
* @param s
* @param e
* @return boolean
* @throws @author fh
* @Title: compareDate
* @Description: TODO(日期比较 如果s > = e 返回true 否则返回false)
*/
public static boolean compareDate(String s, String e) {
if (fomatDate(s) == null || fomatDate(e) == null) {
return false;
}
return fomatDate(s).getTime() >= fomatDate(e).getTime();
}
/**
* 格式化日期
*
* @param date
* @return
*/
public static Date fomatDate(String date) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
return fmt.parse(date);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 校验日期是否合法
*
* @param s
* @return
*/
public static boolean isValidDate(String s) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
fmt.parse(s);
return true;
} catch (Exception e) {
// 如果throw java.text.ParseException或者NullPointerException就说明格式不对
return false;
}
}
/**
* @param startTime
* @param endTime
* @return
*/
public static int getDiffYear(String startTime, String endTime) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
// long aa=0;
int years = (int) (((fmt.parse(endTime).getTime() - fmt.parse(startTime).getTime()) / (1000 * 60 * 60 * 24))
/ 365);
return years;
} catch (Exception e) {
// 如果throw java.text.ParseException或者NullPointerException就说明格式不对
return 0;
}
}
/**
* <li>功能描述时间相减得到天数
*
* @param beginDateStr
* @param endDateStr
* @return long
* @author Administrator
*/
public static long getDaySub(String beginDateStr, String endDateStr) {
long day = 0;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate = null;
Date endDate = null;
try {
beginDate = format.parse(beginDateStr);
endDate = format.parse(endDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
// System.out.println("相隔的天数="+day);
return day;
}
/**
* 得到n天之后的日期
*
* @param days
* @return
*/
public static String getAfterDayDate(String days) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdfd.format(date);
return dateStr;
}
/**
* 得到n天之后是周几
*
* @param days
* @return
*/
public static String getAfterDayWeek(String days) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("E");
String dateStr = sdf.format(date);
return dateStr;
}
/**
* 计算年龄生日格式yyyy-MM-dd
*
* @param birth
* @return
*/
public static String getAge(String birth) {
int cYear = Integer.parseInt(getYear());
String[] births = birth.split("-");
int year = Integer.parseInt(births[0]);
if (cYear <= year) {
return "0";
}
int cMonth = Integer.parseInt(getMonth());
int cDay = Integer.parseInt(getToday());
int month = Integer.parseInt(births[1]);
int day = Integer.parseInt(births[2]);
int age = cYear - year;
if (cMonth - month > 0) {
return String.valueOf(age);
}
if (cDay - day > 0) {
return String.valueOf(age);
}
return String.valueOf(age - 1);
}
/**
* 获取本周周一的日期
*/
public static String weekStartDate(String pattern) {
return new DateTime().dayOfWeek().withMinimumValue().toString(pattern);
}
/**
* 获取本周周一的日期
*/
public static Date weekStartDate() {
return new DateTime().dayOfWeek().withMinimumValue().toDate();
}
/**
* 获取本周最后一天
*
* @return
*/
public static String weekEndDate(String pattern) {
return new DateTime().dayOfWeek().withMaximumValue().toString(pattern);
}
/**
* 获取本周最后一天
*
* @return
*/
public static Date weekEndDate() {
return new DateTime().dayOfWeek().withMaximumValue().toDate();
}
/**
* 获取本月开始日期
*
* @param pattern
* @return
*/
public static String monthStartDate(String pattern) {
return new DateTime().dayOfMonth().withMinimumValue().toString(pattern);
}
/**
* 获取本月开始日期
*
* @param pattern
* @return
*/
public static Date monthStartDate() {
return new DateTime().dayOfMonth().withMinimumValue().toDate();
}
/**
* 获取本月结束日期
*
* @param pattern
* @return
*/
public static String monthEndDate(String pattern) {
return new DateTime().dayOfMonth().withMaximumValue().toString(pattern);
}
/**
* 获取本月结束日期
*
* @return
*/
public static Date monthEndDate() {
return new DateTime().dayOfMonth().withMaximumValue().toDate();
}
/**
* 格式化日期
*
* @param parseLong
* @param format
* @return
*/
public static String formatDate(long parseLong, String format) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormat.format(new Date(parseLong));
}
/**
* 获取前几天的日期带格式
*
* @param day
* @param format
* @return
*/
public static String getBeforeDate(int day, String format) {
DateTime time = new DateTime().plusDays(-day);
return sdfDay.format(time.toDate());
}
/**
* 计算时间差
*
* @param startTime
* @param endTime
* @param format
* @return
*/
public static long getTimeConsuming(String startTime, String endTime, String format) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
long start = simpleDateFormat.parse(startTime).getTime();
long end = simpleDateFormat.parse(endTime).getTime();
long useTime = end - start;
return useTime < 0 ? 0 : useTime;
}
/**
* 计算年龄
*
* @param birthday yyyy-MM-dd
* @return
*/
public static int getAgeByBirthday(String birthday) {
int age = 0;
String[] days = getDay().split("-");
String[] births = birthday.split("-");
int year = Integer.parseInt(days[0]);
int birthYear = Integer.parseInt(births[0]);
int month = Integer.parseInt(days[1]);
int birthMonth = Integer.parseInt(births[1]);
int day = Integer.parseInt(days[2]);
int birthDay = Integer.parseInt(births[2]);
// 判断年龄是否相等
if (year - birthYear > 0) {
if (month - birthMonth > 0) {
return year - birthYear;
} else if (month - birthMonth == 0) {
if (day - birthDay > 0) {
return year - birthYear;
}
return year - birthYear - 1;
}
return year - birthYear - 1;
}
return age;
}
/**
* 获得上下午标识
*
* @return
*/
public static String getAmPm() {
DateTime dateTime = new DateTime();
int hour = dateTime.getHourOfDay();
if (hour < 13) {
return AM;
}
return PM;
}
}