jdk8的localDate和Calendar日历类组合完成日期计算

  对于日期的计算,虽然可以手写,但是也挺繁琐的,首先你得考虑平年闰年,你得考虑每个月多少天,然后再结合自己的业务,嵌入进去。

进行日期的加减操作,虽然可以写个工具类,但是在开发工程中,能引用能方便还是尽量方便的。SE中的Calendar日历类,就可以帮我们来处

理日期计算的问题,localDate则更方便于我们处理年月日。

/**
     * 下次保养日期
     * @param byrq
     * @param zxzqdw
     * @return
     */
    String getXcbyzq(String byrq,String zxzqdw,Integer zxzq ){
        String s=null;
        java.time.LocalDate localDate = null;
        if(byrq != null && !"".equals(byrq)&& zxzqdw != null
                &&  !"".equals(zxzqdw) && zxzq != null&& !"".equals(zxzq)){
            LocalDate parse = LocalDate.parse(byrq);
           s= transLocalDate(parse, zxzq, zxzqdw);
        }
        return s;
    }

    /**
     * jdk1.8 localDate +Calendar日历
     * @param parse
     * @param zxzq
     * @param zxzqdw
     * @return
     */
    String transLocalDate(LocalDate parse,Integer zxzq,String zxzqdw){
        Integer year = null;
        Integer month=null;
        Integer day= null;
        Date resultDate = null;
        Calendar calendar = Calendar.getInstance();
        year = parse.getYear();
        month =parse.getMonthOfYear();
        day = parse.getDayOfMonth();
        switch (zxzqdw){
            case "年":
                year = parse.getYear()+ zxzq;
                break;
            case "月":
                month = parse.getMonthOfYear()+ zxzq;
                break;
            case "日":
                day = parse.getDayOfMonth()+ zxzq;
                break;
            case "季":
                month = parse.getMonthOfYear()+ zxzq*3;
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + zxzqdw);
        }
        calendar.set(year,month,day);
        resultDate = calendar.getTime();
        return dateStr(resultDate);
    }
View Code

 

package com.hainei.service.impl.wp.sbgl;

import com.hainei.common.constants.BaseConstant;
import com.hainei.common.enums.YesOrNo;
import com.hainei.common.token.JwtTokenUtil;
import com.hainei.mapper.base.BaseLogMapper;
import com.hainei.mapper.base.BaseUserMapper;
import com.hainei.mapper.wp.aqzd.WpFileMapper;
import com.hainei.mapper.wp.aqzd.WpGzzdglMapper;
import com.hainei.mapper.wp.aqzd.WpZdpsjlMapper;
import com.hainei.mapper.wp.fileManage.WpFileManageMapper;
import com.hainei.mapper.wp.sbgl.WpYfbyMapper;
import com.hainei.mapper.wp.sbgl.WpYfbyjlMapper;
import com.hainei.mapper.wp.xcgl.WpSbxxMapper;
import com.hainei.mapper.wp.xcgl.WpTzsbMapper;
import com.hainei.pojo.bo.wp.fileManage.WpFileManageBO;
import com.hainei.pojo.bo.wp.sbgl.WpYfbyBO;
import com.hainei.pojo.model.base.BaseLog;
import com.hainei.pojo.model.wp.fileManage.WpFileManage;
import com.hainei.pojo.model.wp.sbgl.WpYfby;
import com.hainei.pojo.model.wp.sbgl.WpYfbyjl;
import com.hainei.pojo.model.wp.xcgl.WpSbxx;
import com.hainei.pojo.model.wp.xcgl.WpTzsb;
import com.hainei.pojo.vo.wp.fileManage.WpFileManageVO;
import com.hainei.pojo.vo.wp.sbgl.WpYfbyVO;
import com.hainei.service.base.BaseDataTableService;
import com.hainei.service.base.BaseOrganizationService;
import com.hainei.service.wp.aqzd.WpFileService;
import com.hainei.service.wp.sbgl.WpYfbyService;
import com.hainei.service.wp.zyaqgl.WpZypNumService;
import org.joda.time.LocalDate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User:wq
 * Date:2021/1/4
 * Time: 18:34
 * Description:
 */
@Service
@Transactional
public class WpYfbyServiceImpl implements WpYfbyService {
    @Autowired
    private WpYfbyMapper wpYfbyMapper;
    @Autowired
    private WpYfbyjlMapper wpYfbyjlMapper;
    @Autowired
    private WpTzsbMapper tzsbMapper;
    @Autowired
    private WpSbxxMapper sbxxMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private BaseOrganizationService organizationService;
    @Autowired
    private BaseDataTableService dataTableService;
    @Autowired
    private WpZypNumService zypNumService;
    @Autowired
    private BaseUserMapper userMapper;

    @Override
    public void addRecord(WpYfbyBO wpYfbyBO) {
        String token = request.getHeader(BaseConstant.ACCESS_TOKEN);
        String userId = JwtTokenUtil.getUserId(token);
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        WpYfby wpYfby = new WpYfby();
        BeanUtils.copyProperties(wpYfbyBO, wpYfby);
        wpYfby.setId(id);
        //wpYfby.setFileNum(zypNumService.getZypNum("AQWJ"));
        wpYfby.setIsDeleted(YesOrNo.NO.type);
        wpYfby.setGmtCreatedOn(new Date());
        wpYfby.setGmtCreatedBy(userId);
        //添加数据权限表
        Set<String> organizationIdsByUserId = organizationService.getOrganizationIdsByUserId(userId);
        //3.插入数据权限
        dataTableService.insert(organizationIdsByUserId, id);
        wpYfbyMapper.insertSelective(wpYfby);
        WpYfbyjl wpYfbyjl = new WpYfbyjl();
        BeanUtils.copyProperties(wpYfby,wpYfbyjl);
        wpYfbyjl.setYfbyId(id);
        wpYfbyjlMapper.insert(wpYfbyjl);
    }

    @Override
    public void deleteByIds(List<String> ids) {
        for (String id :
                ids) {
            WpYfby wpYfby = new WpYfby();
            wpYfby.setId(id);
            wpYfby.setIsDeleted(YesOrNo.YES.type);
            wpYfbyMapper.updateByPrimaryKeySelective(wpYfby);
        }
    }

    @Override
    public void updateRecord(WpYfbyBO wpYfbyBO) {
        String token = request.getHeader(BaseConstant.ACCESS_TOKEN);
        String userId = JwtTokenUtil.getUserId(token);
        WpYfby wpYfby = new WpYfby();
        wpYfby.setGmtUpdatedBy(userId);
        BeanUtils.copyProperties(wpYfbyBO, wpYfby);
        wpYfbyMapper.updateByPrimaryKeySelective(wpYfby);
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        //添加数据权限表
        Set<String> organizationIdsByUserId = organizationService.getOrganizationIdsByUserId(userId);
        //3.插入数据权限
        dataTableService.insert(organizationIdsByUserId, id);
        WpYfbyjl wpYfbyjl = new WpYfbyjl();
        BeanUtils.copyProperties(wpYfby,wpYfbyjl);
        wpYfbyjl.setId(id);
        wpYfbyjl.setYfbyId(wpYfbyBO.getId());
        wpYfbyjlMapper.insertSelective(wpYfbyjl);
    }

    @Override
    public WpYfbyVO getById(String id) {
        WpYfbyVO byId = wpYfbyMapper.getById(id);
        putWfValue(byId);
        return byId;
    }

    @Override
    public List<WpYfbyVO> listAll(WpYfbyBO wpYfbyBO) {
        String token = request.getHeader(BaseConstant.ACCESS_TOKEN);
        String userId = JwtTokenUtil.getUserId(token);
        wpYfbyBO.setGmtCreatedBy(userId);
        List<WpYfbyVO> wpFileManageVOS = wpYfbyMapper.listAllRecord(wpYfbyBO);
        wpFileManageVOS.stream().filter(p -> p != null).forEach(p -> putWfValue(p));
        return wpFileManageVOS;
    }

    @Override
    public List<WpYfbyVO> listHistory(WpYfbyBO wpYfbyBO) {
        String token = request.getHeader(BaseConstant.ACCESS_TOKEN);
        String userId = JwtTokenUtil.getUserId(token);
        wpYfbyBO.setGmtCreatedBy(userId);
        List<WpYfbyVO> wpFileManageVOS = wpYfbyjlMapper.listAllRecord(wpYfbyBO);
        wpFileManageVOS.stream().filter(p -> p != null).forEach(p -> putWfValue(p));
        return wpFileManageVOS;
    }


    void putWfValue(WpYfbyVO yfbyVO) {
        if(yfbyVO !=null){
            if(yfbyVO.getZrr() != null && !"".equals(yfbyVO.getZrr())){
                yfbyVO.setZrr(userMapper.getById(yfbyVO.getZrr()).getName());
            }
            if(yfbyVO.getByrq() != null && !"".equals(yfbyVO.getByrq())){
                yfbyVO.setXcbyzq(getXcbyzq(yfbyVO.getByrq(),yfbyVO.getZxzqdw(),yfbyVO.getZxzq()));
            }
            if(yfbyVO.getSbmc() != null){
                WpTzsb wpTzsb = tzsbMapper.selectByPrimaryKey(yfbyVO.getSbmc());
                WpSbxx wpSbxx = sbxxMapper.selectByPrimaryKey(yfbyVO.getSbmc());
                if(wpSbxx!=null){
                    yfbyVO.setSbmc(wpSbxx.getSbmc());
                }
                if(wpTzsb!= null){
                    yfbyVO.setSbmc(wpTzsb.getSbmc());
                }
            }

        }
    }




    /**
     * 下次保养日期
     * @param byrq
     * @param zxzqdw
     * @return
     */
    String getXcbyzq(String byrq,String zxzqdw,Integer zxzq ){
        String s=null;
        java.time.LocalDate localDate = null;
        if(byrq != null && !"".equals(byrq)&& zxzqdw != null
                &&  !"".equals(zxzqdw) && zxzq != null&& !"".equals(zxzq)){
            LocalDate parse = LocalDate.parse(byrq);
           s= transLocalDate(parse, zxzq, zxzqdw);
        }
        return s;
    }

    /**
     * jdk1.8 localDate +Calendar日历
     * @param parse
     * @param zxzq
     * @param zxzqdw
     * @return
     */
    String transLocalDate(LocalDate parse,Integer zxzq,String zxzqdw){
        Integer year = null;
        Integer month=null;
        Integer day= null;
        Date resultDate = null;
        Calendar calendar = Calendar.getInstance();
        year = parse.getYear();
        month =parse.getMonthOfYear();
        day = parse.getDayOfMonth();
        switch (zxzqdw){
            case "年":
                year = parse.getYear()+ zxzq;
                break;
            case "月":
                month = parse.getMonthOfYear()+ zxzq;
                break;
            case "日":
                day = parse.getDayOfMonth()+ zxzq;
                break;
            case "季":
                month = parse.getMonthOfYear()+ zxzq*3;
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + zxzqdw);
        }
        calendar.set(year,month,day);
        resultDate = calendar.getTime();
        return dateStr(resultDate);
    }
//    String transLocalDate(LocalDate parse,Integer zxzq,String zxzqdw){
//        Integer year = null;
//        Integer month=null;
//        Integer day= null;
//        java.time.LocalDate result =null;
//        year = parse.getYear();
//        month =parse.getMonthOfYear();
//        day = parse.getDayOfMonth();
//        switch (zxzqdw){
//            case "年":
//                year = parse.getYear()+ zxzq;
//                break;
//            case "月":
//                month = parse.getMonthOfYear()+ zxzq; break;
//            case "日":
//                day = parse.getDayOfMonth()+ zxzq;
//            case "季":
//                month = parse.getMonthOfYear()+ zxzq*3;
//                break;
//            default:
//                throw new IllegalStateException("Unexpected value: " + zxzqdw);
//        }
//        List<Integer> list = transDate(zxzqdw, year, month, day);
//        if(list.size()>0){
//            result= java.time.LocalDate.of(list.get(0), list.get(1),list.get(2));
//        }
//        if(month<12 && day<30){
//            result= java.time.LocalDate.of(year, month,day);
//        }
//        return result.toString();
//    }

    List<Integer> transDate(String zxzqdw, Integer year,Integer month,Integer day){
        List<Integer> list = new ArrayList<>();
        if("季".equals(zxzqdw)){
            zxzqdw = "月";
        }
        if(month>12||day>30){
            switch (zxzqdw){
                case "月":
                    if (month>12){
                        int i = month / 12;
                        month = month % 12;
                        year= year + i;
                        list.add(year);
                        list.add(month);
                        list.add(day);
                    } break;
                case "日":
                    if(day > 30){
                        int addMonth =  day / 30;
                         day = day % 30;
                        month= month + addMonth;
                        if(month>12){
                           int i = month / 12;
                            month = month % 12;
                            year= year + i;
                            list.add(year);
                            list.add(month);
                            list.add(day);
                        }
                        list.add(year);
                        list.add(month);
                        list.add(day);
                    } break;
            }
        }
        return list;
    }

    Date dateFormate(String byrq,String format){
        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
             date = sdf.parse(byrq);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    String dateStr(Date date){
        String dateStr = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(date!=null){
            dateStr = sdf.format(date);
        }
        return dateStr;
    }
}
View Code

 

Calendar 

 @Override
    public List<ZonesParkEvaluateResultVO> history(String companyAuth) {
        List<ZonesParkEvaluateResultVO> lists = zonesParkEvaluateResultMapper.history(companyAuth);
        for (ZonesParkEvaluateResultVO vo : lists) {
            Calendar c = Calendar.getInstance();
            c.setTime(vo.getGmtCreatedOn());
            c.add(Calendar.DATE, 30);
            Date endDate = c.getTime();
            String inDate = new DateDiff().dateDiff(new Date(), endDate);
            vo.setInDate(inDate);
        }
        return lists;
    }
View Code

DateDiff
package com.hainei.common.utils;

import java.util.Date;

/**
 * 计算持续时间
 * @Author: WangJunsa
 * @Date: 2019/11/26 16:59
 * @Version 1.0
 */
public class DateDiff {
    public String dateDiff(Date startTime, Date endTime) {
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        long ns = 1000;// 一秒钟的毫秒数
        long diff;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        // 获得两个时间的毫秒时间差异

        diff = endTime.getTime() - startTime.getTime();
        day = diff / nd;// 计算差多少天
        hour = diff % nd / nh + day * 24;// 计算差多少小时
        min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟
        sec = diff % nd % nh % nm / ns;// 计算差多少秒
        // 输出结果
        return day + "天" + (hour - day * 24) + "小时"
                + (min - day * 24 * 60) + "分钟" + sec + "秒";

    }




}
View Code

 

posted @ 2021-02-26 18:03  wq9  阅读(184)  评论(0编辑  收藏  举报