万年历,可以查 曰、月、年,缓存到redis,直接抓取使用,

代码部分记录,提供阅读并使用,仅供参考

效果图


import com.github.pagehelper.PageInfo;
import com.paascloud.PublicUtil;
import com.paascloud.SnowFlake;
import com.paascloud.StringUtils;
import com.paascloud.core.config.ExceptionHandlingAsyncTaskExecutor;
import com.paascloud.core.utils.RedisUtil;
import com.paascloud.provider.config.exception.BusinessException;
import com.paascloud.provider.mapper.*;
import com.paascloud.provider.model.common.TcsConstants;
import com.paascloud.provider.model.dto.QueryCronDto;
import com.paascloud.provider.model.dto.QueryListDto;
import com.paascloud.provider.model.dto.TaskSaveDto;
import com.paascloud.provider.model.dto.TaskUpdateDto;
import com.paascloud.provider.model.dto.holiday.HolidayDto;
import com.paascloud.provider.model.pojo.*;
import com.paascloud.provider.model.pojo.base.HolidayPojo;
import com.paascloud.provider.model.service.HolidayFeignApi;
import com.paascloud.provider.model.vo.*;
import com.paascloud.provider.model.vo.user.UacUserVo;
import com.paascloud.provider.service.IAddCronService;
import com.paascloud.provider.service.ITaskCalendarService;
import com.paascloud.provider.utils.CronUtils;
import com.paascloud.provider.utils.DateUtils;
import com.paascloud.provider.utils.redis.RedisCommonService;
import com.paascloud.provider.utils.redis.TcsMonthService;
import com.paascloud.provider.utils.redis.TcsYearService;
import com.paascloud.provider.utils.tcsCalendar.SimpleCalendar;
import com.paascloud.wrapper.Wrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskCalendarServiceImpl implements ITaskCalendarService {

    @Autowired
    private AssignmentConfMapper confMapper;

    @Autowired
    private AssignmentCrontabMapper crontabMapper;

    @Resource
    private ExceptionHandlingAsyncTaskExecutor taskExecutor;

    @Autowired
    private AssignmentCrontabJobMapper crontabJobMapper;

    @Autowired
    private IAddCronService addCronService;

    @Autowired
    private AssignmentRemindTimeMapper remindTimeMapper;

    @Autowired
    private AssignmentRemindUserMapper remindUserMapper;

    @Autowired
    private RedisCommonService redisCommonService;
    @Autowired
    private TcsMonthService tcsMonthService;
    @Autowired
    private RedisUtil redisUtils;
    @Autowired
    private HolidayFeignApi holidayFeignApi;


    /**
     * 根据类型查询数据
     *
     * @param token
     * @param dto
     * @return
     */
    @Override
    public TaskListVo findListByType(String token, QueryCronDto dto) {
        UacUserVo userVo = redisCommonService.getUserByToken(token);
        //拼装查询条件
        QueryListDto selectQuery = this.createQuery(dto);
        selectQuery.setOrgId(dto.getOrgId());
        TaskListVo vo = new TaskListVo();
        vo.setType(dto.getType());
        HolidayDto holidayDto=new HolidayDto();
        holidayDto.setOrganizationId(dto.getOrgId());
        Integer year=Integer.parseInt(dto.getDayTime().substring(0,4));
        holidayDto.setYear(year);
        //获取当前年限的项目节假日
        Wrapper<PageInfo<HolidayPojo>> result = holidayFeignApi.selectCalender(holidayDto, "1", 1, 366);
        PageInfo<HolidayPojo> pojoPageInfo = result.getResult();
        List<HolidayPojo> holidayPojoList = pojoPageInfo.getList();
        vo.setHolidayList(holidayPojoList);
        switch (dto.getType()) {
            case "day": {
                dayStatment(selectQuery, vo);
                break;
            }
            case "week": {
                weekStatment(selectQuery, vo);
                break;
            }
            case "month": {
                monthlyStatement(dto.getDayTime(), dto.getOrgId(), selectQuery, vo);
                break;
            }
            case "year": {
                vo.setMonthVoList(null);
                yearStatment(dto.getDayTime(), dto.getOrgId(), vo);
                break;
            }
            default: {
                throw new BusinessException(500, "请输入正确的类型");
            }
        }
        vo.setHolidayList(null);
        return vo;
    }

    @Override
    public void updateRedisTask(String token, TaskSaveDto dto) {
        taskExecutor.execute(() -> this.updateMonthTask(dto.getStartTime(), dto.getEndTime(), dto.getOrganizationId()));
    }

    public void taskYearDataInital(String dateTime, String orgId, TaskListVo vo) {
        this.yearStatment(dateTime, orgId, vo);
    }

    
    private void yearStatment(String dateTime, String orgId, TaskListVo vo) {
        /*List<AssignmentConfPojo> list = confMapper.selectListByDate(selectQuery);
        //数据转MAP
        Map<String, Set> map = new HashedMap();
        getEveryDayTask(map, list);//获取天的任务
        //计算区间内日期
        List<Date> lDate = DateUtils.findDates(selectQuery.getStartDate(), selectQuery.getEndDate());
        List<YearVo> weekVoList = new ArrayList<>();
        for (Date dates : lDate) {
            YearVo yearVo = new YearVo();
            getLday(dates, map, yearVo);
            weekVoList.add(yearVo);
        }*/

        //一年也就是12个月
        String year = dateTime.substring(0, 4);
        List<List<? extends DayVo>> yearVoList=new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            String yearMonth;
            if (String.valueOf(i).length() == 1) {
                yearMonth = year + "-0" + i + "-01";
            } else {
                yearMonth = year + "-" + i + "-01";
            }
            log.info("处理月的日期"+yearMonth);
            QueryListDto selectQuery = DateUtils.getMonthDate(yearMonth);
            monthlyStatement(yearMonth, orgId, selectQuery, vo);
            List<? extends DayVo> dayVos = vo.getMonthVoList();
            yearVoList.add(dayVos);
        }
        vo.setYearVoList(yearVoList);
    }

    
    private void dayStatment(QueryListDto selectQuery, TaskListVo vo) {
        List<String> dateLsit=new ArrayList<>();
        SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd");
        String start = sdformat.format(selectQuery.getStartDate());
        dateLsit.add(start);
        selectQuery.setDateList(dateLsit);
        List<AssignmentConfPojo> list = confMapper.selectListByDate(selectQuery);
        //数据转MAP
        Map<String, Set> map = new HashedMap();
        getEveryDayTask(map, list);//获取天的任务
        Map<String, HolidayPojo> holidayPojoMap = getHolidayPojoMap(vo);
        //计算区间内日期
        List<Date> lDate = DateUtils.findDates(selectQuery.getStartDate(), selectQuery.getEndDate());
        List<DayVo> dayVoList = new ArrayList<>();
        for (Date dates : lDate) {
            DayVo dayVo = new DayVo();
            getLday(dates, map, dayVo);
            if(PublicUtil.isNotEmpty(holidayPojoMap)) {
                HolidayPojo holidayPojo = holidayPojoMap.get(sdformat.format(dates));
                if(PublicUtil.isNotEmpty(holidayPojo)) {
                    dayVo.setType(holidayPojo.getType());
                }
            }
            dayVoList.add(dayVo);
        }
        vo.setMonthVoList(dayVoList);
    }

    
    private void weekStatment(QueryListDto selectQuery, TaskListVo vo) {
        SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd");
        //计算区间内日期
        List<Date> lDate = DateUtils.findDates(selectQuery.getStartDate(), selectQuery.getEndDate());
        selectQuery.setDateList(getDateLsit(lDate));
        List<AssignmentConfPojo> list = confMapper.selectListByDate(selectQuery);
        //数据转MAP
        Map<String, Set> map = new HashedMap();
        getEveryDayTask(map, list);//获取天的任务
        Map<String, HolidayPojo> holidayPojoMap = getHolidayPojoMap(vo);
        List<WeekVo> weekVoList = new ArrayList<>();
        for (Date dates : lDate) {
            WeekVo weekVo = new WeekVo();
            getLday(dates, map, weekVo);
            if(PublicUtil.isNotEmpty(holidayPojoMap)) {
                HolidayPojo holidayPojo = holidayPojoMap.get(sdformat.format(dates));
                if(PublicUtil.isNotEmpty(holidayPojo)) {
                    weekVo.setType(holidayPojo.getType());
                }
            }
            weekVoList.add(weekVo);
        }
        vo.setMonthVoList(weekVoList);
    }

    private List<String> getDateLsit(List<Date> lDate){
        List<String> dateLsit=new ArrayList<>();
        lDate.stream().forEach(date -> {
            SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = sdformat.format(date);
            dateLsit.add(dateStr);
        });
        return dateLsit;
    }

    
    private void updateMonthTask(Date startTime, Date endTime, String orgId) {
        log.info("数据缓存开始...");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String start = simpleDateFormat.format(startTime);
        String end = simpleDateFormat.format(endTime);
        String[] startStr = start.split("-");
        String[] endStr = end.split("-");
        //如果是同年,当月
        if (startStr[0].equals(endStr[0]) && startStr[1].equals(endStr[1])) {
            updateMonthTaskData(orgId, start);
        } else {
            //如果是跨年、其实都是时间差月差
            if (!startStr[0].equals(endStr[0])) {
                //先计算跨月是几年有几个月
                int diff = Integer.parseInt(endStr[0]) - Integer.parseInt(startStr[0]);
                if (diff > 0) {
                    String tempYear = startStr[0];//从开始的年限计算每次加1
                    int monthSum;
                    int tempMonth;
                    for (int j = 0; j <= diff; j++) {//循环相差年份数量
                        if (startStr[0].equals(tempYear)) {//当前年月份差
                            tempMonth = Integer.parseInt(startStr[1]);
                            monthSum=12;
                        } else if (endStr[0].equals(tempYear)) {//最后一年
                            tempMonth = 1;
                            monthSum=Integer.parseInt(endStr[1]);
                        } else {//中间年份的月数
                            tempMonth = 1;
                            monthSum=12;
                        }
                        String yearMonth;
                        for (int i = tempMonth; i <= monthSum; i++) {//每一年的阶段月份
                            if (i < 10) {
                                yearMonth = tempYear + "-0" + i + "-01";
                            } else {
                                yearMonth = tempYear + "-" + i + "-01";
                            }
                            updateMonthTaskData(orgId, yearMonth);
                        }
                        tempYear = String.valueOf((Integer.parseInt(tempYear) + 1));//缓存完了一次年份+1
                    }
                }
            } else {
                //如果是同年,跨月,先计算跨月是有几个月
                String year = startStr[0];
                int tempMonth = Integer.parseInt(startStr[1]);
                String yearMonth;
                for (int i = tempMonth; i <= 12; i++) {//每一年的阶段月份
                    if (i < 10) {
                        yearMonth = year + "-0" + i + "-01";
                    } else {
                        yearMonth = year + "-" + i + "-01";
                    }
                    updateMonthTaskData(orgId, yearMonth);
                }
            }
        }
    }

    /*   private void updateYearTaskData(String orgId,String dateTime){
           String year = dateTime.substring(0, 4);
           for (int i = 1; i <= 12; i++) {
               String yearMonth;
               if (String.valueOf(i).length() == 1) {
                   yearMonth = year + "-0" + i + "-01";
               } else {
                   yearMonth = year + "-" + i + "-01";
               }
               updateMonthTaskData(orgId, yearMonth);
           }
       }*/
    private void updateMonthTaskData(String orgId, String dateTime) {
        String[] str = dateTime.split("-");
        String year = str[0];
        String month = str[1];
        QueryListDto selectQuery = DateUtils.getMonthDate(dateTime);
        TaskListVo vo = new TaskListVo();
        vo.setType("month");
        //计算区间内日期
        List<Date> lDate = DateUtils.findDates(selectQuery.getStartDate(), selectQuery.getEndDate());
        selectQuery.setDateList(getDateLsit(lDate));
        List<AssignmentConfPojo> list = confMapper.selectListByDate(selectQuery);
        //数据转MAP
        Map<String, Set> map = new HashedMap();
        getEveryDayTask(map, list);//获取天的任务
        List<MonthVo> monthVoList = new ArrayList<>();
        for (Date dates : lDate) {
            MonthVo monthVo = new MonthVo();
            getLday(dates, map, monthVo);
            monthVoList.add(monthVo);
        }
        vo.setMonthVoList(monthVoList);
        //把数据存入缓存中
        tcsMonthService.setMonthTask(orgId, year, month, vo);
    }

    /**
     * 组装月数据
     *
     * @param selectQuery
     * @param vo
     */
    private void monthlyStatement(String dateTime, String orgId, QueryListDto selectQuery, TaskListVo vo) {
        Map<String, HolidayPojo> holidayPojoMap = getHolidayPojoMap(vo);
        //先从缓存拿数据
        String[] str = dateTime.split("-");
        String year = str[0];
        String month = str[1];
        if(StringUtils.isNotEmpty(vo.getInital()) && vo.getInital().equals("0")){
            String key = TcsConstants.TCS_TASK_YEAR + ":" + orgId + ":" + year + ":" + month;
            redisUtils.delRedisByKey(key);
        }
        TaskListVo result = tcsMonthService.getMothTask(orgId, year, month);
        if (PublicUtil.isNotEmpty(result)) {
            List<? extends DayVo> monthVoList = result.getMonthVoList();
            monthVoList.stream().forEach(o->{
                StringBuffer key = new StringBuffer(String.valueOf(o.getSYear()));
                if (String.valueOf(o.getSMonth()).length() == 1) {
                    key.append("-0").append(String.valueOf(o.getSMonth()));
                } else {
                    key.append("-").append(String.valueOf(o.getSMonth()));
                }
                if (String.valueOf(o.getSDay()).length() == 1) {
                    key.append("-0").append(String.valueOf(o.getSDay()));
                } else {
                    key.append("-").append(String.valueOf(o.getSDay()));
                }
                HolidayPojo holidayPojo = holidayPojoMap.get(key.toString());
                    if(PublicUtil.isNotEmpty(holidayPojo)) {
                        o.setType(holidayPojo.getType());
                    }
            });
            vo.setMonthVoList(monthVoList);
            return;
        }
        selectQuery.setOrgId(orgId);
        //计算区间内日期
        List<Date> lDate = DateUtils.findDates(selectQuery.getStartDate(), selectQuery.getEndDate());
        selectQuery.setDateList(getDateLsit(lDate));
        List<AssignmentConfPojo> list = confMapper.selectListByDate(selectQuery);
        //数据转MAP
        Map<String, Set> map = new HashedMap();
        getEveryDayTask(map, list);//获取天的任务

        SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd");
        List<MonthVo> monthVoList = new ArrayList<>();
        for (Date dates : lDate) {
            MonthVo monthVo = new MonthVo();
            getLday(dates, map, monthVo);
            if(PublicUtil.isNotEmpty(holidayPojoMap)) {
                HolidayPojo holidayPojo = holidayPojoMap.get(sdformat.format(dates));
                if(PublicUtil.isNotEmpty(holidayPojo)) {
                    monthVo.setType(holidayPojo.getType());
                }
            }
            monthVoList.add(monthVo);
        }
        vo.setMonthVoList(monthVoList);
        //把数据存入缓存中
        tcsMonthService.setMonthTask(orgId, year, month, vo);
    }

    public Map<String, HolidayPojo> getHolidayPojoMap(TaskListVo vo){
        Map<String, HolidayPojo> holidayPojoMap = new HashMap<>();
        if(PublicUtil.isNotEmpty(vo.getHolidayList())) {
            List<HolidayPojo> holidayPojoList = vo.getHolidayList();//平台节假日
            holidayPojoList.stream().forEach(o -> {
                StringBuffer key = new StringBuffer(o.getYear().toString());
                if (o.getMonth().toString().length() == 1) {
                    key.append("-0").append(o.getMonth().toString());
                } else {
                    key.append("-").append(o.getMonth().toString());
                }
                if (o.getDay().toString().length() == 1) {
                    key.append("-0").append(o.getDay().toString());
                } else {
                    key.append("-").append(o.getDay().toString());
                }
                holidayPojoMap.put(key.toString(), o);
            });
        }
        return holidayPojoMap;
    }

    
    private void getLday(Date dates, Map<String, Set> map, DayVo dayVo) {
        SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleCalendar.Element element = null;
        try {
            element = SimpleCalendar.getCalendarDetail(dates);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new BusinessException(500, "查询失败");
        }
        if (element == null) {
            throw new BusinessException(500, "查询失败");
        }
        BeanUtils.copyProperties(element, dayVo);
        if (null != map.get(sdformat.format(dates))) {
//            dayVo.setConfId(map.get(sdformat.format(dates)));
            dayVo.setDayTaskVos(map.get(sdformat.format(dates)));
        }
        dayVo.setSolarFestival(dayVo.getSolarFestival().trim());
        //log.info("阳历:{}-{}-{} 农历:{}月{}  周{}  农历节假日:{} 阳历节假日:{}",
        //        element.getsYear(), element.getsMonth(), element.getsDay(),
        //       element.getlMonthChinese(), element.getcDay(), element.getWeek(), element.getSolarFestival(), element.getLunarFestival());
    }

    
    private void getEveryDayTask(Map<String, Set> map, List<AssignmentConfPojo> list) {
        //将数据拆成每天存放
        list.stream().forEach(o -> {
            List<Date> lDate = DateUtils.findDates(o.getStartTime(), o.getEndTime());
            lDate.stream().forEach(date -> {
                SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd");
                String dateStr = sdformat.format(date);
                DayTaskVo dayTaskVo=new DayTaskVo();
                BeanUtils.copyProperties(o,dayTaskVo);
                if (null != map.get(dateStr)) {
                    Set<DayTaskVo> set = map.get(dateStr);
//                    set.add(o.getId());
                    set.add(dayTaskVo);
                    map.put(dateStr, set);
                } else {
                    Set<DayTaskVo> set = new HashSet<>();
//                    set.add(o.getId());
                    set.add(dayTaskVo);
                    map.put(dateStr, set);
                }
            });
        });
    }


    /**
     * 组装查询条件
     *
     * @param dto
     * @return
     */
    public QueryListDto createQuery(QueryCronDto dto) {
        QueryListDto queryDto = new QueryListDto();
        switch (dto.getType()) {
            case "day": {
                return DateUtils.geDayDate(dto.getDayTime());
            }
            case "week": {
                return DateUtils.getWeekDate(dto.getDayTime());
            }
            case "month": {
                return DateUtils.getMonthDate(dto.getDayTime());
            }
            case "year": {
                return DateUtils.getYearDate(dto.getDayTime());
            }
            default: {
                throw new BusinessException(500, "请输入正确的类型");
            }
        }
    }
}

 

 


import com.alibaba.fastjson.JSON;
import com.paascloud.DateUtil;
import com.paascloud.provider.config.exception.BusinessException;
import com.paascloud.provider.model.dto.QueryListDto;
import com.paascloud.provider.utils.tcsCalendar.SimpleCalendar;
import lombok.extern.slf4j.Slf4j;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 日期操作类
 */
@Slf4j
public class DateUtils {

    /**
     * 获取一段时间内的所有日期
     *
     * @param begin
     * @param end
     * @return
     */
    public static List<Date> getDay(Date begin, Date end) {
        List<Date> dateList = new ArrayList();
        dateList.add(begin);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(begin);
        boolean bContinue = true;
        while (bContinue) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            if (end.after(calendar.getTime())) {
                dateList.add(calendar.getTime());
            } else {
                break;
            }
        }
        dateList.add(end);
        return dateList;
    }

    /**
     * 根据日期获取当天是周几
     *
     * @param datetime 日期
     * @return 周几
     */
    public static String dateToWeek(String datetime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        Date date;
        try {
            date = sdf.parse(datetime);
            cal.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        return weekDays[w];
    }

    /**
     * 根据日期获取当天是周几
     *
     * @param datetime 日期
     * @return 周几
     */
    public static int dateToWeek(Date datetime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(datetime);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        return w;
    }

    /**
     * 获取某段时间内的周一(二等等)的日期
     *
     * @param dataBegin 开始日期
     * @param dataEnd   结束日期
     * @param weekDays  获取周几,1-6代表周一到周六。0代表周日
     * @return 返回日期List
     */
    public static List<String> getDayOfWeekWithinDateInterval(String dataBegin, String dataEnd, int weekDays) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> dateResult = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        String[] dateInterval = {dataBegin, dataEnd};
        Date[] dates = new Date[dateInterval.length];
        for (int i = 0; i < dateInterval.length; i++) {
            String[] ymd = dateInterval[i].split("[^\\d]+");
            cal.set(Integer.parseInt(ymd[0]), Integer.parseInt(ymd[1]) - 1, Integer.parseInt(ymd[2]));
            dates[i] = cal.getTime();
        }
        for (Date date = dates[0]; date.compareTo(dates[1]) <= 0; ) {
            cal.setTime(date);
            if (cal.get(Calendar.DAY_OF_WEEK) - 1 == weekDays) {
                String format = sdf.format(date);
                dateResult.add(format);
            }
            cal.add(Calendar.DATE, 1);
            date = cal.getTime();
        }
        return dateResult;
    }


    /**
     * 计算某个时间 相减前的时间
     *
     * @param startDate
     * @param time
     * @return
     */
    public static Date getDateTime(Date startDate, Integer time) {
        //转化成分钟
        long times = time * 60 * 1000;
        Date beforeDate = new Date(startDate.getTime() - times);
        return beforeDate;
    }

    /**
     * 计算某个时间 相加的时间
     *
     * @param startDate
     * @param time
     * @return
     */
    public static Date addDateTime(Date startDate, Integer time) {
        //转化成分钟
        long times = time * 60 * 1000;
        Date beforeDate = new Date(startDate.getTime() + times);
        return beforeDate;
    }

    /**
     * 获取当前日期的周一至周日
     *
     * @return
     */
    public static QueryListDto getWeekDate(String dateTime) {
        try {
            QueryListDto dto = new QueryListDto();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cal = Calendar.getInstance();
            Date date;
            try {
                date = sdf.parse(dateTime);
                cal.setTime(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
            cal.setFirstDayOfWeek(Calendar.MONDAY);
            // 获得当前日期是一个星期的第几天
            int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
            if (dayWeek == 1) {
                dayWeek = 8;
            }
            cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
            Date mondayDate = cal.getTime();

            cal.add(Calendar.DATE, 4 + cal.getFirstDayOfWeek());
            Date sundayDate = cal.getTime();
            String weekBegin = sdf.format(mondayDate);
            String weekEnd = sdf.format(sundayDate);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            dto.setStartDate(simpleDateFormat.parse(weekBegin + " 00:00:00"));
            dto.setEndDate(simpleDateFormat.parse(weekEnd + " 23:59:59"));
            return dto;
        } catch (ParseException ex) {
            throw new BusinessException(500, "日期转换失败");
        }
    }

    /**
     * 获取当天
     *
     * @param dateTime
     * @return
     */
    public static QueryListDto geDayDate(String dateTime) {
        try {
            QueryListDto dto = new QueryListDto();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            dto.setStartDate(simpleDateFormat.parse(dateTime + " 00:00:00"));
            dto.setEndDate(simpleDateFormat.parse(dateTime + " 23:59:59"));
            return dto;
        } catch (ParseException ex) {
            throw new BusinessException(500, "日期转换失败");
        }
    }

    //得到本月的第一天
    public static String getMonthFirstDay(String dateTime) {
        SimpleDateFormat firstDay = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        try {
            Date date = firstDay.parse(dateTime);
            calendar.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar.set(Calendar.DAY_OF_MONTH,
                calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        return firstDay.format(calendar.getTime());
    }

    //得到本月的最后一天
    public static String getMonthLastDay(String dateTime) {
        SimpleDateFormat lastDay = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        try {
            Date date = lastDay.parse(dateTime);
            calendar.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar.set(Calendar.DAY_OF_MONTH,
                calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return lastDay.format(calendar.getTime());
    }

    /**
     * 获取当前日期月
     *
     * @param dateTime
     * @return
     */
    public static QueryListDto getMonthDate(String dateTime) {
        try {
            QueryListDto dto = new QueryListDto();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            dto.setStartDate(simpleDateFormat.parse(getMonthFirstDay(dateTime) + " 00:00:00"));
            dto.setEndDate(simpleDateFormat.parse(getMonthLastDay(dateTime) + " 23:59:59"));
            return dto;
        } catch (ParseException ex) {
            throw new BusinessException(500, "日期转换失败");
        }
    }

    /**
     * 获取某年第一天日期
     *
     * @param year 年份
     * @return Date
     */
    public static String getYearFirst(int year) {
        SimpleDateFormat lastDay = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return lastDay.format(currYearFirst);
    }

    /**
     * 获取某年最后一天日期
     *
     * @param year 年份
     * @return Date
     */
    public static String getYearLast(int year) {
        SimpleDateFormat lastDay = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();
        return lastDay.format(currYearLast);
    }

    /**
     * 获取当年的第一天
     *
     * @param dateTime
     * @return
     */
    public static String getCurrYearFirst(String dateTime) {
        SimpleDateFormat lastDay = new SimpleDateFormat("yyyy-MM-dd");
        Calendar currCal = Calendar.getInstance();
        try {
            Date date = lastDay.parse(dateTime);
            currCal.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearFirst(currentYear);
    }

    /**
     * 获取当年的最后一天
     *
     * @param dateTime
     * @return
     */
    public static String getCurrYearLast(String dateTime) {
        SimpleDateFormat lastDay = new SimpleDateFormat("yyyy-MM-dd");
        Calendar currCal = Calendar.getInstance();
        try {
            Date date = lastDay.parse(dateTime);
            currCal.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearLast(currentYear);
    }

    /**
     * 获取年份日期
     *
     * @param dateTime
     * @return
     */
    public static QueryListDto getYearDate(String dateTime) {
        try {
            QueryListDto dto = new QueryListDto();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            dto.setStartDate(simpleDateFormat.parse(getCurrYearFirst(dateTime) + " 00:00:00"));
            dto.setEndDate(simpleDateFormat.parse(getCurrYearLast(dateTime) + " 23:59:59"));
            return dto;
        } catch (ParseException ex) {
            throw new BusinessException(500, "日期转换失败");
        }
    }

    public static long get_D_Plaus_1(Calendar c) {
        c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + 1);
        return c.getTimeInMillis();
    }

    /**
     * 获取某段时间内全部日期
     *
     * @param dBegin
     * @param dEnd
     * @return
     */
    public static List<Date> findDates(Date dBegin, Date dEnd) {
        List lDate = new ArrayList();
//        lDate.add(dBegin);
//        Calendar calBegin = Calendar.getInstance();
//        // 使用给定的 Date 设置此 Calendar 的时间
//        calBegin.setTime(dBegin);
//        Calendar calEnd = Calendar.getInstance();
//        // 使用给定的 Date 设置此 Calendar 的时间
//        calEnd.setTime(dEnd);
//        // 测试此日期是否在指定日期之后
//        while (dEnd.after(calBegin.getTime())) {
//            // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
//            calBegin.add(Calendar.DAY_OF_MONTH, 1);
//            lDate.add(calBegin.getTime());
//        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cal = Calendar.getInstance();
            cal.setTime(sdf.parse(sdf.format(dBegin)));
            for (long d = cal.getTimeInMillis(); d <= sdf.parse(sdf.format(dEnd)).getTime(); d = get_D_Plaus_1(cal)) {
                lDate.add(sdf.parse(sdf.format(d)));
            }
        } catch (ParseException ex) {
            throw new BusinessException(500, "日期转换失败");
        }
        return lDate;
    }

    /**
     * @Author luojiawen
     * @Description 时间格式yyyy-MM-dd
     * @Date 2020/9/29 16:52
     * @Param [startTime, endTime]
     * @return int
     **/
    public static int getMonthDifference(Date startTime,Date endTime){
        Calendar bef = Calendar.getInstance();
        Calendar aft = Calendar.getInstance();
        bef.setTime(startTime);
        aft.setTime(endTime);
        int surplus = aft.get(Calendar.DATE) - bef.get(Calendar.DATE);
        int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
        int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
        surplus = surplus <= 0 ? 1 : 0;
        return (Math.abs(month + result) + surplus);
    }


    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        List<Date> list = DateUtils.getDay(new Date(), sdf.parse("2020-10-01 23:59:59"));
//        for (Date date : list) {
//            System.out.println(sdf.format(date));
//        }
//
//        //当前周几
//        System.out.println(DateUtils.dateToWeek(sdf.format(new Date())));
//        int weekDays = DateUtils.dateToWeek(new Date());
//        List<String> dateList = DateUtils.getDayOfWeekWithinDateInterval(sdf.format(new Date()), "2020-10-01 23:59:59", weekDays);
//        System.out.println(dateList);

        Date date = DateUtils.getDateTime(sdf.parse("2020-09-17 23:59:59"), 1440);
        System.out.println(sdf.format(date));
        System.out.println(CronUtils.getCron(date));

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        QueryListDto dto = DateUtils.getYearDate("2010-09-16");
        System.out.println(JSON.toJSON(dto));
        System.out.println(simpleDateFormat.format(dto.getStartDate()) + "    " + simpleDateFormat.format(dto.getEndDate()));


        dto = DateUtils.getMonthDate("2020-09-01");
        System.out.println(simpleDateFormat.format(dto.getStartDate()) + "    " + simpleDateFormat.format(dto.getEndDate()));


        List<Date> lDate = DateUtils.findDates(dto.getStartDate(), dto.getEndDate());
        lDate.stream().forEach(o -> {
            System.out.println(simpleDateFormat.format(o));
        });

        System.out.println("------------------------------------------------");
//        dto =  DateUtils.getWeekDate("2020-09-21");
        DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = dateFormat1.parse("2020-09-23");
        Date endDate = dateFormat1.parse("2020-09-24");
        List<Date> lDate2 = DateUtils.findDates(startDate, endDate);
        lDate2.stream().forEach(o -> {
            System.out.println(simpleDateFormat.format(o));
        });
//        Calendar cal = Calendar.getInstance();
//        String start = "2020-01-01";
//        String end = "2020-12-31";
//        SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd");
//        Date dBegin = sdformat.parse(start);
//        Date dEnd = sdformat.parse(end);
//        List<Date> lDate = findDates(dBegin, dEnd);
//        for (Date dates : lDate) {
//            SimpleCalendar.Element element = SimpleCalendar.getCalendarDetail(dates);
//            log.info("阳历:{}-{}-{} 农历:{}月{}  周{}  节假日:{} {}",
//                    element.getsYear(), element.getsMonth(), element.getsDay(),
//                    element.getlMonthChinese(), element.getcDay(), element.getWeek(), element.getSolarFestival(),element.getLunarFestival());
//        }


    }


    public static void main1(String[] args) throws ParseException {
        String beginDate = "2020-09-01";//开始时间
        String endDate = "2020-09-30";//结束时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(beginDate));

        for (long d = cal.getTimeInMillis(); d <= sdf.parse(endDate).getTime(); d = get_D_Plaus_1(cal)) {
            System.out.println(sdf.format(d));
        }

    }





}

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * cron格式转换
 */
public class CronUtils {
    private static final SimpleDateFormat sdf = new SimpleDateFormat("ss mm HH dd MM ? yyyy");

    /***
     *  功能描述:日期转换cron表达式
     * @param date
     * @return
     */
    public static String formatDateByPattern(Date date) {
        String formatTimeStr = null;
        if (Objects.nonNull(date)) {
            formatTimeStr = sdf.format(date);
        }
        return formatTimeStr;
    }

    /***
     * convert Date to cron, eg "0 07 10 15 1 ? 2016"
     * @param date  : 时间点
     * @return
     */
    public static String getCron(Date date) {
        return formatDateByPattern(date);
    }
}

 


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @Description: 计算农历节假日信息
 * SimpleCalendar.Element element=SimpleCalendar.getCalendarDetail("2019-06-06","yyyy-MM-dd");
 * element=SimpleCalendar.getCalendarDetail("2019-06-04","yyyy-MM-dd");
 */
@Slf4j
public class SimpleCalendar {
    long[] lunarInfo = new long[]{
            0x4bd8, 0x4ae0, 0xa570, 0x54d5, 0xd260, 0xd950, 0x5554, 0x56af, 0x9ad0, 0x55d2,
            0x4ae0, 0xa5b6, 0xa4d0, 0xd250, 0xd255, 0xb54f, 0xd6a0, 0xada2, 0x95b0, 0x4977,
            0x497f, 0xa4b0, 0xb4b5, 0x6a50, 0x6d40, 0xab54, 0x2b6f, 0x9570, 0x52f2, 0x4970,
            0x6566, 0xd4a0, 0xea50, 0x6a95, 0x5adf, 0x2b60, 0x86e3, 0x92ef, 0xc8d7, 0xc95f,
            0xd4a0, 0xd8a6, 0xb55f, 0x56a0, 0xa5b4, 0x25df, 0x92d0, 0xd2b2, 0xa950, 0xb557,
            0x6ca0, 0xb550, 0x5355, 0x4daf, 0xa5b0, 0x4573, 0x52bf, 0xa9a8, 0xe950, 0x6aa0,
            0xaea6, 0xab50, 0x4b60, 0xaae4, 0xa570, 0x5260, 0xf263, 0xd950, 0x5b57, 0x56a0,
            0x96d0, 0x4dd5, 0x4ad0, 0xa4d0, 0xd4d4, 0xd250, 0xd558, 0xb540, 0xb6a0, 0x95a6,
            0x95bf, 0x49b0, 0xa974, 0xa4b0, 0xb27a, 0x6a50, 0x6d40, 0xaf46, 0xab60, 0x9570,
            0x4af5, 0x4970, 0x64b0, 0x74a3, 0xea50, 0x6b58, 0x5ac0, 0xab60, 0x96d5, 0x92e0,
            0xc960, 0xd954, 0xd4a0, 0xda50, 0x7552, 0x56a0, 0xabb7, 0x25d0, 0x92d0, 0xcab5,
            0xa950, 0xb4a0, 0xbaa4, 0xad50, 0x55d9, 0x4ba0, 0xa5b0, 0x5176, 0x52bf, 0xa930,
            0x7954, 0x6aa0, 0xad50, 0x5b52, 0x4b60, 0xa6e6, 0xa4e0, 0xd260, 0xea65, 0xd530,
            0x5aa0, 0x76a3, 0x96d0, 0x4afb, 0x4ad0, 0xa4d0, 0xd0b6, 0xd25f, 0xd520, 0xdd45,
            0xb5a0, 0x56d0, 0x55b2, 0x49b0, 0xa577, 0xa4b0, 0xaa50, 0xb255, 0x6d2f, 0xada0,
            0x4b63, 0x937f, 0x49f8, 0x4970, 0x64b0, 0x68a6, 0xea5f, 0x6b20, 0xa6c4, 0xaaef,
            0x92e0, 0xd2e3, 0xc960, 0xd557, 0xd4a0, 0xda50, 0x5d55, 0x56a0, 0xa6d0, 0x55d4,
            0x52d0, 0xa9b8, 0xa950, 0xb4a0, 0xb6a6, 0xad50, 0x55a0, 0xaba4, 0xa5b0, 0x52b0,
            0xb273, 0x6930, 0x7337, 0x6aa0, 0xad50, 0x4b55, 0x4b6f, 0xa570, 0x54e4, 0xd260,
            0xe968, 0xd520, 0xdaa0, 0x6aa6, 0x56df, 0x4ae0, 0xa9d4, 0xa4d0, 0xd150, 0xf252,
            0xd520};
    List<Element> elements = new ArrayList<Element>();
    public static Map<String, SimpleCalendar> cache = new HashMap<String, SimpleCalendar>();
    long[] solarMonth = new long[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    String[] Gan = new String[]{"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"};
    String[] Zhi = new String[]{"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"};
    String[] Animals = new String[]{"鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"};
    String[] solarTerm = new String[]{"小寒", "大寒", "立春", "雨水", "惊蛰", "春分", "清明", "谷雨", "立夏", "小满", "芒种", "夏至", "小暑", "大暑", "立秋", "处暑", "白露", "秋分", "寒露", "霜降", "立冬", "小雪", "大雪", "冬至"};
    int[] sTermInfo = new int[]{0, 21208, 42467, 63836, 85337, 107014, 128867, 150921, 173149, 195551, 218072, 240693, 263343, 285989, 308563, 331033, 353350, 375494, 397447, 419210, 440795, 462224, 483532, 504758};
    char[] nStr1 = new char[]{'日', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'};
    String[] nStr2 = new String[]{"初", "十", "廿", "卅", " "};

    static String[] monthChinese = new String[]{"一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"};
    static String[] dayChinese = new String[]{"一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", "二十一", "二十二", "二十三", "二十四", "二十五", "二十六", "二十七", "二十八", "二十九", "三十", "三十一"};
    char[] jcName0 = new char[]{'建', '除', '满', '平', '定', '执', '破', '危', '成', '收', '开', '闭'};
    char[] jcName1 = new char[]{'闭', '建', '除', '满', '平', '定', '执', '破', '危', '成', '收', '开'};
    char[] jcName2 = new char[]{'开', '闭', '建', '除', '满', '平', '定', '执', '破', '危', '成', '收'};
    char[] jcName3 = new char[]{'收', '开', '闭', '建', '除', '满', '平', '定', '执', '破', '危', '成'};
    char[] jcName4 = new char[]{'成', '收', '开', '闭', '建', '除', '满', '平', '定', '执', '破', '危'};
    char[] jcName5 = new char[]{'危', '成', '收', '开', '闭', '建', '除', '满', '平', '定', '执', '破'};
    char[] jcName6 = new char[]{'破', '危', '成', '收', '开', '闭', '建', '除', '满', '平', '定', '执'};
    char[] jcName7 = new char[]{'执', '破', '危', '成', '收', '开', '闭', '建', '除', '满', '平', '定'};
    char[] jcName8 = new char[]{'定', '执', '破', '危', '成', '收', '开', '闭', '建', '除', '满', '平'};
    char[] jcName9 = new char[]{'平', '定', '执', '破', '危', '成', '收', '开', '闭', '建', '除', '满'};
    char[] jcName10 = new char[]{'满', '平', '定', '执', '破', '危', '成', '收', '开', '闭', '建', '除'};
    char[] jcName11 = new char[]{'除', '满', '平', '定', '执', '破', '危', '成', '收', '开', '闭', '建'};

    //国历节日  *表示放假日
    String[] sFtv = new String[]{
            "0101*元旦",
            "0106  中国13亿人口日",
            "0110  中国110宣传日",

            "0202  世界湿地日",
            "0204  世界抗癌症日",
            "0210  世界气象日",
            "0214  情人节",
            "0221  国际母语日",
            "0207  国际声援南非日",

            "0303  全国爱耳日",
            "0308  妇女节",
            "0312  植树节 孙中山逝世纪念日",
            "0315  消费者权益保护日",
            "0321  世界森林日",
            "0322  世界水日",
            "0323  世界气象日",
            "0324  世界防治结核病日",

            "0401  愚人节",
            "0407  世界卫生日",
            "0422  世界地球日",

            "0501*国际劳动节",
            "0504  中国青年节",
            "0505  全国碘缺乏病日",
            "0508  世界红十字日",
            "0512  国际护士节",
            "0515  国际家庭日",
            "0517  世界电信日",
            "0518  国际博物馆日",
            "0519  中国汶川地震哀悼日 全国助残日",
            "0520  全国学生营养日",
            "0522  国际生物多样性日",
            "0523  国际牛奶日",
            "0531  世界无烟日",

            "0601  国际儿童节",
            "0605  世界环境日",
            "0606  全国爱眼日",
            "0617  防治荒漠化和干旱日",
            "0623  国际奥林匹克日",
            "0625  全国土地日",
            "0626  国际反毒品日",

            "0701  建党节 香港回归纪念日",
            "0707  抗日战争纪念日",
            "0711  世界人口日",

            "0801  八一建军节",
            "0815  日本正式宣布无条件投降日",

            "0908  国际扫盲日",
            "0909  **逝世纪念日",
            "0910  教师节",
            "0916  国际臭氧层保护日",
            "0917  国际和平日",
            "0918  九·一八事变纪念日",
            "0920  国际爱牙日",
            "0927  世界旅游日",
            "0928  孔子诞辰",

            "1001*国庆节 国际音乐节 国际老人节",
            "1002  国际减轻自然灾害日",
            "1004  世界动物日",
            "1007  国际住房日",
            "1008  世界视觉日 全国高血压日",
            "1009  世界邮政日",
            "1010  辛亥革命纪念日 世界精神卫生日",
            "1015  国际盲人节",
            "1016  世界粮食节",
            "1017  世界消除贫困日",
            "1022  世界传统医药日",
            "1024  联合国日",
            "1025  人类天花绝迹日",
            "1026  足球诞生日",
            "1031  万圣节",

            "1107  十月社会主义革命纪念日",
            "1108  中国记者日",
            "1109  消防宣传日",
            "1110  世界青年节",
            "1112  孙中山诞辰",
            "1114  世界糖尿病日",
            "1117  国际大学生节",

            "1201  世界艾滋病日",
            "1203  世界残疾人日",
            "1209  世界足球日",
            "1210  世界人权日",
            "1212  西安事变纪念日",
            "1213  南京大屠杀",
            "1220  澳门回归纪念日",
            "1221  国际篮球日",
            "1224  平安夜",
            "1225  圣诞节 世界强化免疫日",
            "1226  **诞辰"};
    //农历节日  *表示放假日
    String[] lFtv = new String[]{
            "0101*春节",
            "0102*大年初二",
            "0103*大年初三",
            "0104*大年初四",
            "0105*大年初五",
            "0106*大年初六",
            "0107*大年初七",
            "0105  路神生日",
            "0115  元宵节",
            "0202  龙抬头",
            "0219  观世音圣诞",
            "0404  寒食节",
            "0408  佛诞节 ",
            "0505*端午节",
            "0606  天贶节 姑姑节",
            "0624  彝族火把节",
            "0707  七夕情人节",
            "0714  鬼节(南方)",
            "0715  盂兰节",
            "0730  地藏节",
            "0815*中秋节",
            "0909  重阳节",
            "1001  祭祖节",
            "1117  阿弥陀佛圣诞",
            "1208  腊八节 释迦如来成道日",
            "1223  过小年",
            "1229*腊月二十九",
            "0100*除夕"};
    //某月的第几个星期几; 5,6,7,8 表示到数第 1,2,3,4 个星期几
    String[] wFtv = new String[]{
            "0110  黑人节",
            "0150  世界麻风日",
            "0121  日本成人节",
            "0520  母亲节",
            "0530  全国助残日",
            "0630  父亲节",
            "0716  合作节",
            "0730  被奴役国家周",
            "0932  国际和平日",
            "0940  国际聋人节 世界儿童日",
            "1011  国际住房日",
            "1144  感恩节"};
    private Long length;//公历当月天数
    private int firstWeek;  //公历当月1日星期几

    public static Element getCalendarDetail(Date date) throws ParseException {

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        String cacheKey = (year + "-" + month);
        SimpleCalendar lunarCalendarUtil = null;
        if (false) {
            lunarCalendarUtil = cache.get(cacheKey);
        } else {
            lunarCalendarUtil = new SimpleCalendar();
            lunarCalendarUtil.calendar(year, month);
            cache.put(cacheKey, lunarCalendarUtil);
        }

        return lunarCalendarUtil.getElements().get(cal.get(Calendar.DATE) - 1);
    }

    public static Element getCalendarDetail(String date, String pattern) throws ParseException {
        SimpleDateFormat df2 = new SimpleDateFormat(pattern);
        return getCalendarDetail(df2.parse(date));
    }

    public List<Element> getElements() {
        return elements;
    }

    public void setElements(List<Element> elements) {
        this.elements = elements;
    }

    public void calendar(int y, int m) throws ParseException {
        Date sDObj = null;
        Lunar lDObj = null;
        Boolean lL = null;
        Long lD2 = null;
        Integer lY = null, lM = null, lD = 1, lX = 0, tmp1, tmp2, lM2, lY2 = null, tmp3, dayglus, bsg, xs, xs1, fs, fs1, cs, cs1 = null;
        String cY, cM, cD; //年柱,月柱,日柱
        Integer[] lDPOS = new Integer[3];
        Integer n = 0;
        Integer firstLM = 0;
        String dateString = y + "-" + (m + 1) + "-" + 1;
        sDObj = new SimpleDateFormat("yyyy-MM-dd").parse(dateString);

        this.length = solarDays(y, m);    //公历当月天数
        this.firstWeek = sDObj.getDay();    //公历当月1日星期几

        年柱 1900年立春后为庚子年(60进制36)
        if (m < 2) {
            cY = cyclical(y - 1900 + 36 - 1);
        } else {
            cY = cyclical(y - 1900 + 36);
        }
        int term2 = sTerm(y, 2); //立春日期

        月柱 1900年1月小寒以前为 丙子月(60进制12)
        int firstNode = sTerm(y, m * 2);//返回当月「节」为几日开始
        cM = cyclical((y - 1900) * 12 + m + 12);

        lM2 = (y - 1900) * 12 + m + 12;
        //当月一日与 1900/1/1 相差天数
        //1900/1/1与 1970/1/1 相差25567日, 1900/1/1 日柱为甲戌日(60进制10)
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        df2.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date date = df2.parse("" + y + "-" + (m + 1) + "-" + 1 + " 00:00:00");

        long dayCyclical = date.getTime() / 86400000 + 25567 + 10;
         long dayCyclical =date.getTime() / 86400000 + 25567 + 10;
        SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        for (int i = 0; i < this.length; i++) {
            if (i == 18) {
                int b = 5;
            }
            if (lD > lX) {
                sDObj = df3.parse("" + y + "-" + (m + 1) + "-" + (i + 1) + " 00:00:00");   //当月一日日期
                lDObj = new Lunar(sDObj);     //农历
                lY = lDObj.year;           //农历年
                lM = lDObj.month;          //农历月
                lD = lDObj.day;            //农历日
                lL = lDObj.isLeap;         //农历是否闰月
                lX = lL ? leapDays(lY) : monthDays(lY, lM); //农历当月最后一天

                if (n == 0) {
                    firstLM = lM;
                }

                lDPOS[n++] = i - lD + 1;
            }

            //依节气调整二月分的年柱, 以立春为界
            if (m == 1 && (i + 1) == term2) {
                cY = cyclical(y - 1900 + 36);
                lY2 = (y - 1900 + 36);
            }
            //依节气月柱, 以「节」为界
            if ((i + 1) == firstNode) {
                cM = cyclical((y - 1900) * 12 + m + 13);
                lM2 = (y - 1900) * 12 + m + 13;
            }
            //日柱
            cD = cyclical(dayCyclical + i);
            lD2 = (dayCyclical + i);
            Element element = new Element(y, m + 1, i + 1, (nStr1[(i + this.firstWeek) % 7]),
                    lY, lM, lD++, lL,
                    cY, cM, cD);
            element.setcDay(cDay(element.getlDay()));
            int paramterLy2 = lY2 == null ? -1 : (lY2 % 12);
            int paramterLm2 = lM2 == null ? -1 : lM2 % 12;
            long paramterLd2 = lD2 == null ? -1 : lD2 % 12;
            int paramterLy2b = lY2 == null ? -1 : lY2 % 10;
            int paramterLy2c = (int) (lD2 == null ? -1 : lD2 % 10);
            int paramterLld = lD == null ? -1 : lD - 1;
            element.setSgz5(CalConv2(paramterLy2, paramterLm2, (int) paramterLd2, paramterLy2b, paramterLy2c, lM, paramterLld, m + 1, cs1 == null ? -1 : cs1));
            element.setSgz3(cyclical6(lM2 % 12, (int) ((lD2) % 12)));
            elements.add(element);


        }

        //节气
        tmp1 = sTerm(y, m * 2) - 1;
        tmp2 = sTerm(y, m * 2 + 1) - 1;
        elements.get(tmp1).solarTerms = solarTerm[m * 2];
        elements.get(tmp2).solarTerms = solarTerm[m * 2 + 1];
        if (m == 3) {
            elements.get(tmp1).color = "red"; //清明颜色
        }

        Pattern p = Pattern.compile("^(\\d{2})(\\d{2})([\\s\\*])(.+)$");
        //国历节日
        for (String i : sFtv) {
            Matcher matcher = p.matcher(i);
            if (matcher.matches()) {
                if (i.equals("1212  西安事变纪念日")) {
                    int j = 2;
                }
                if (Integer.valueOf(matcher.group(1)).intValue() == (m + 1)) {
                    elements.get(Integer.valueOf(matcher.group(2)) - 1).solarFestival += matcher.group(4) + "";
                    if (matcher.group(3).equals('*')) {
                        elements.get(Integer.valueOf(matcher.group(0)) - 1).color = "red";
                    }
                }
            }
        }

        p = Pattern.compile("^(\\d{2})(.{2})([\\s\\*])(.+)$");
        //农历节日
        for (String i : lFtv) {
            Matcher matcher = p.matcher(i);
            if (matcher.matches()) {
                tmp1 = Integer.valueOf(matcher.group(1)) - firstLM;
                if (tmp1 == -11) {
                    tmp1 = 1;
                }
                if (tmp1 >= 0 && tmp1 < n) {
                    tmp2 = lDPOS[tmp1] + Integer.valueOf(matcher.group(2)) - 1;
                    if (tmp2 >= 0 && tmp2 < this.length) {
                        elements.get(tmp2).lunarFestival += matcher.group(4);
                        if (matcher.group(3).equals("*")) {
                            elements.get(tmp2).color = "red";
                        }
                    }
                }
            }
        }

        //复活节只出现在3或4月
        if (m == 2 || m == 3) {
            Easter estDay = new Easter(y);
            if (m == estDay.m) {
                elements.get(estDay.d - 1).solarFestival = elements.get(estDay.d - 1).solarFestival + " 复活节(Easter Sunday)";
            }
        }


        //黑色星期五
        if ((this.firstWeek + 12) % 7 == 5) {
            elements.get(12).solarFestival += "黑色星期五";
        }

        //今日
        //if (y == tY && m == tM) this[tD - 1].isToday = true;
    }

    //==============================返回公历 y年某m+1月的天数
    public long solarDays(int y, int m) {
        if (m == 1) {
            return (((y % 4 == 0) && (y % 100 != 0) || (y % 400 == 0)) ? 29 : 28);
        } else {
            return (solarMonth[m]);
        }
    }

    //============================== 返回阴历 (y年,m+1月)
    public char cyclical6(int num, int num2) {
        if (num == 0) {
            return (jcName0[num2]);
        }
        if (num == 1) {
            return (jcName1[num2]);
        }
        if (num == 2) {
            return (jcName2[num2]);
        }
        if (num == 3) {
            return (jcName3[num2]);
        }
        if (num == 4) {
            return (jcName4[num2]);
        }
        if (num == 5) {
            return (jcName5[num2]);
        }
        if (num == 6) {
            return (jcName6[num2]);
        }
        if (num == 7) {
            return (jcName7[num2]);
        }
        if (num == 8) {
            return (jcName8[num2]);
        }
        if (num == 9) {
            return (jcName9[num2]);
        }
        if (num == 10) {
            return (jcName10[num2]);
        }
        if (num == 11) {
            return (jcName11[num2]);
        }
        return '0';
    }

    public String CalConv2(int yy, int mm, int dd, int y, int d, int m, int dt, int nm, int nd) {
        int dy = d + dd;
        if ((yy == 0 && dd == 6) || (yy == 6 && dd == 0) || (yy == 1 && dd == 7) || (yy == 7 && dd == 1) || (yy == 2 && dd == 8) || (yy == 8 && dd == 2) || (yy == 3 && dd == 9) || (yy == 9 && dd == 3) || (yy == 4 && dd == 10) || (yy == 10 && dd == 4) || (yy == 5 && dd == 11) || (yy == 11 && dd == 5)) {
            return "<FONT color=#0000A0>日值岁破 大事不宜</font>";
        } else if ((mm == 0 && dd == 6) || (mm == 6 && dd == 0) || (mm == 1 && dd == 7) || (mm == 7 && dd == 1) || (mm == 2 && dd == 8) || (mm == 8 && dd == 2) || (mm == 3 && dd == 9) || (mm == 9 && dd == 3) || (mm == 4 && dd == 10) || (mm == 10 && dd == 4) || (mm == 5 && dd == 11) || (mm == 11 && dd == 5)) {
            return "<FONT color=#0000A0>日值月破 大事不宜</font>";
        } else if ((y == 0 && dy == 911) || (y == 1 && dy == 55) || (y == 2 && dy == 111) || (y == 3 && dy == 75) || (y == 4 && dy == 311) || (y == 5 && dy == 9) || (y == 6 && dy == 511) || (y == 7 && dy == 15) || (y == 8 && dy == 711) || (y == 9 && dy == 35)) {
            return "<FONT color=#0000A0>日值上朔 大事不宜</font>";
        } else if ((m == 1 && dt == 13) || (m == 2 && dt == 11) || (m == 3 && dt == 9) || (m == 4 && dt == 7) || (m == 5 && dt == 5) || (m == 6 && dt == 3) || (m == 7 && dt == 1) || (m == 7 && dt == 29) || (m == 8 && dt == 27) || (m == 9 && dt == 25) || (m == 10 && dt == 23) || (m == 11 && dt == 21) || (m == 12 && dt == 19)) {
            return "<FONT color=#0000A0>日值杨公十三忌 大事不宜</font>";
        } else {
            return "0";
        }
    }

    //    public Date getUtcDate(String dateStr){
//        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        df2.setTimeZone(TimeZone.getTimeZone("UTC"));
//        Date date = df2.parse("1900-01-06 02:05:00");
//    }
    //============================== 传入 offsenew Datet 返回干支, 0=甲子
    public String cyclical(long num) {
        return (Gan[(int) (num % 10)] + Zhi[(int) (num % 12)]);
    }

    //======================  中文日期
    public String cDay(int d) {
        String s;

        switch (d) {
            case 10:
                s = "初十";
                break;
            case 20:
                s = "二十";
                break;
            case 30:
                s = "三十";
                break;
            default:
                s = nStr2[Double.valueOf(Math.floor(d / 10)).intValue()];
                s += nStr1[d % 10];
        }
        return (s);
    }

    //===== 某年的第n个节气为几日(从0小寒起算)
    public int sTerm(int y, int n) throws ParseException {
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        df2.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date date = df2.parse("1900-01-06 02:05:00");
        Long utcTime2 = date.getTime();
        BigDecimal time2 = new BigDecimal(31556925974.7).multiply(new BigDecimal(y - 1900)).add(new BigDecimal(sTermInfo[n]).multiply(BigDecimal.valueOf(60000L)));
        BigDecimal time = time2.add(BigDecimal.valueOf(utcTime2));
        Date offDate = new Date(time.longValue());
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        cal.setTime(offDate);
        int utcDate = cal.get(Calendar.DATE);
        //日期从0算起
        return utcDate;
    }

    //====================================== 返回农历 y年闰哪个月 1-12 , 没闰返回 0
    public Long leapMonth(int y) {
        long lm = lunarInfo[y - 1900] & 0xf;
        return (lm == 0xf ? 0 : lm);
    }

    //====================================== 返回农历 y年的总天数
    public Long lYearDays(int y) {
        long i, sum = 348;
        for (i = 0x8000; i > 0x8; i >>= 1) {
            sum += (lunarInfo[y - 1900] & i) != 0 ? 1 : 0;
        }
        return (sum + leapDays(y));
    }

    //====================================== 返回农历 y年闰月的天数
    public int leapDays(int y) {
        if (leapMonth(y) != 0) {
            return ((lunarInfo[y - 1899] & 0xf) == 0xf ? 30 : 29);
        } else {
            return 0;
        }
    }

    //====================================== 返回农历 y年m月的总天数
    private int monthDays(int y, int m) {
        return ((lunarInfo[y - 1900] & (0x10000 >> m)) != 0 ? 30 : 29);
    }

    public class Lunar {
        private int year;
        private boolean isLeap;
        private int month;
        private int day;

        public Lunar(Date objDate) throws ParseException {
            int i, leap = 0, temp = 0;
            SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            df2.setTimeZone(TimeZone.getTimeZone("UTC"));
            DateFormat dtFmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date date = df2.parse(dtFmt.format(objDate));
            SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            df3.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date date3 = df3.parse("" + 1900 + "-" + 1 + "-" + 31 + " 00:00:00");
            long time1 = date.getTime();
            long time2 = date3.getTime();
            int offset = (int) ((time1 - time2) / 86400000);
            for (i = 1900; i < 2100 && offset > 0; i++) {
                temp = lYearDays(i).intValue();
                offset -= temp;
            }

            if (offset < 0) {
                offset += temp;
                i--;
            }

            this.year = i;
            leap = leapMonth(i).intValue(); //闰哪个月
            this.isLeap = false;

            for (i = 1; i < 13 && offset > 0; i++) {
                //闰月
                if (leap > 0 && i == (leap + 1) && this.isLeap == false) {
                    --i;
                    this.isLeap = true;
                    temp = leapDays(this.year);
                } else {
                    temp = monthDays(this.year, i);
                }

                //解除闰月
                if (this.isLeap == true && i == (leap + 1)) {
                    this.isLeap = false;
                }
                offset -= temp;
            }

            if (offset == 0 && leap > 0 && i == leap + 1) {
                if (this.isLeap) {
                    this.isLeap = false;
                } else {
                    this.isLeap = true;
                    --i;
                }
            }
            if (offset < 0) {
                offset += temp;
                --i;
            }

            this.month = i;
            this.day = offset + 1;
        }


    }

    public class Easter {
        public int m;
        public int d;

        public Easter(int y) throws ParseException {
            int term2 = sTerm(y, 5); //取得春分日期
            SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            df2.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date dayTerm2 = df2.parse("" + y + "-" + 3 + "-" + term2 + " 00:00:00");//取得春分的公历日期控件(春分一定出现在3月)
            Lunar lDayTerm2 = new Lunar(dayTerm2); //取得取得春分农历
            int lMlen = 0;
            if (lDayTerm2.day < 15) { //取得下个月圆的相差天数
                lMlen = 15 - lDayTerm2.day;
            } else {
                lMlen = (lDayTerm2.isLeap ? leapDays(y) : monthDays(y, lDayTerm2.month)) - lDayTerm2.day + 15;
            }

            //一天等于 1000*60*60*24 = 86400000 毫秒
            Date l15 = new Date(dayTerm2.getTime() + 86400000 * lMlen); //求出第一次月圆为公历几日
            Date dayEaster = new Date(l15.getTime() + 86400000 * (7 - l15.getDay())); //求出下个周日

            this.m = dayEaster.getMonth();
            this.d = dayEaster.getDate();
        }
    }

    public static class Element {
        public int sYear;
        public int sMonth;
        public int sDay;
        public char week;
        public int lYear;
        public int lMonth;
        public String lMonthChinese;
        public String lDayChinese;
        public int lDay;
        public boolean isLeap;
        public String cYear;
        public String cMonth;
        public String cDay;
        public String color;
        public boolean isToday = false;
        public String lunarFestival;
        public String solarFestival;
        public String solarTerms;
        public String sgz5;
        public char sgz3;

        public Element(int sYear, int sMonth, int sDay, char week, int lYear, int lMonth, int lDay, boolean isLeap, String cYear, String cMonth, String cDay) {

            this.isToday = false;
            //瓣句
            this.sYear = sYear;   //公元年4位数字
            this.sMonth = sMonth;  //公元月数字
            this.sDay = sDay;    //公元日数字
            this.week = week;    //星期, 1个中文
            //农历
            this.lYear = lYear;   //公元年4位数字
            this.lMonth = lMonth;  //农历月数字
            this.lDay = lDay;    //农历日数字
            this.isLeap = isLeap;  //是否为农历闰月?
            //中文
            this.lMonthChinese = monthChinese[lMonth - 1];
            this.lDayChinese = dayChinese[lDay - 1];
            //八字
            this.cYear = cYear;   //年柱, 2个中文
            this.cMonth = cMonth;  //月柱, 2个中文
            this.cDay = cDay;    //日柱, 2个中文

            this.color = "";

            this.lunarFestival = ""; //农历节日
            this.solarFestival = ""; //公历节日
            this.solarTerms = ""; //节气
        }

        public String getSgz5() {
            return sgz5;
        }

        public void setSgz5(String sgz5) {
            this.sgz5 = sgz5;
        }

        public char getSgz3() {
            return sgz3;
        }

        public void setSgz3(char sgz3) {
            this.sgz3 = sgz3;
        }

        public int getsYear() {
            return sYear;
        }

        public void setsYear(int sYear) {
            this.sYear = sYear;
        }

        public int getsMonth() {
            return sMonth;
        }

        public void setsMonth(int sMonth) {
            this.sMonth = sMonth;
        }

        public int getsDay() {
            return sDay;
        }

        public void setsDay(int sDay) {
            this.sDay = sDay;
        }

        public char getWeek() {
            return week;
        }

        public void setWeek(char week) {
            this.week = week;
        }

        public int getlYear() {
            return lYear;
        }

        public void setlYear(int lYear) {
            this.lYear = lYear;
        }

        public int getlMonth() {
            return lMonth;
        }

        public void setlMonth(int lMonth) {
            this.lMonth = lMonth;
        }

        public int getlDay() {
            return lDay;
        }

        public void setlDay(int lDay) {
            this.lDay = lDay;
        }

        public boolean isLeap() {
            return isLeap;
        }

        public void setLeap(boolean leap) {
            isLeap = leap;
        }

        public String getcYear() {
            return cYear;
        }

        public void setcYear(String cYear) {
            this.cYear = cYear;
        }

        public String getcMonth() {
            return cMonth;
        }

        public void setcMonth(String cMonth) {
            this.cMonth = cMonth;
        }

        public String getcDay() {
            return cDay;
        }

        public void setcDay(String cDay) {
            this.cDay = cDay;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }

        public boolean isToday() {
            return isToday;
        }

        public void setToday(boolean today) {
            isToday = today;
        }

        public String getLunarFestival() {
            return lunarFestival;
        }

        public void setLunarFestival(String lunarFestival) {
            this.lunarFestival = lunarFestival;
        }

        public String getSolarFestival() {
            return solarFestival;
        }

        public void setSolarFestival(String solarFestival) {
            this.solarFestival = solarFestival;
        }

        public String getSolarTerms() {
            return solarTerms;
        }

        public void setSolarTerms(String solarTerms) {
            this.solarTerms = solarTerms;
        }

        public String getlMonthChinese() {
            return lMonthChinese;
        }

        public void setlMonthChinese(String lMonthChinese) {
            this.lMonthChinese = lMonthChinese;
        }

        public String getlDayChinese() {
            return lDayChinese;
        }

        public void setlDayChinese(String lDayChinese) {
            this.lDayChinese = lDayChinese;
        }
    }

    public static void main(String[] args) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse("2020-10-01");
            Element element = SimpleCalendar.getCalendarDetail(date);
            System.out.println(JSON.toJSON(element));
            log.info("阳历:{}-{}-{} 农历:{}月{}  周{}  节假日:{} 阳历节假日:{}",
                    element.getsYear(), element.getsMonth(), element.getsDay(),
                    element.getlMonthChinese(), element.getcDay(), element.getWeek(), element.getLunarFestival(), element.getSolarFestival()
            );
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

import com.paascloud.PublicUtil;
import com.paascloud.core.utils.RedisUtil;
import com.paascloud.provider.model.common.TcsConstants;
import com.paascloud.provider.model.vo.TaskListVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class TcsMonthService {


    @Autowired
    private RedisUtil redisUtils;


    /**
     * @return void
     * @Author luojiawen
     * @Description 缓存月的数据
     * @Date 2020/9/29 10:06
     * @Param [orgId, time]
     **/
    public void setMonthTask(String orgId, String year, String moth, TaskListVo taskListVo) {
        String key = TcsConstants.TCS_TASK_YEAR + ":" + orgId + ":" + year + ":" + moth;
        Object result = redisUtils.getObject(key);
        if (PublicUtil.isNotEmpty(result)) {
            redisUtils.delRedisByKey(key);
        }
        try {
            redisUtils.setObject(key, taskListVo);
            log.info(year + ":" + moth + "的缓存数据成功");
        } catch (Exception e) {
            log.info("redis存数据失败" + e);
        }
    }

    /**
     * @return com.paascloud.provider.model.vo.TaskListVo
     * @Author luojiawen
     * @Description 从缓存里拿到月的缓存数据
     * @Date 2020/9/29 9:43
     * @Param [orgId, year]
     **/
    public TaskListVo getMothTask(String orgId, String year, String moth) {
        String key = TcsConstants.TCS_TASK_YEAR + ":" + orgId + ":" + year + ":" + moth;
        log.info("redis key:"+key);
        Object result = redisUtils.getObject(key);
        TaskListVo taskListVo = (TaskListVo) result;
        return taskListVo;
    }
}

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 C# 中将询出的数据缓存Redis 中,可以使用 StackExchange.Redis 库,这是 Redis 官方推荐的 C# 客户端。 以下是一个示例代码,用于将询出的数据保存到 Redis 中: ```csharp using StackExchange.Redis; using System; public class RedisCache { private readonly ConnectionMultiplexer _redis; public RedisCache(string connectionString) { _redis = ConnectionMultiplexer.Connect(connectionString); } public void SetData(string key, object data, TimeSpan expireTime) { var db = _redis.GetDatabase(); db.StringSet(key, JsonConvert.SerializeObject(data), expireTime); } public T GetData<T>(string key) { var db = _redis.GetDatabase(); var value = db.StringGet(key); if (value.HasValue) { return JsonConvert.DeserializeObject<T>(value); } return default(T); } } ``` 这里使用了 Newtonsoft.Json 库将数据序列化成 JSON 字符串,并将过期时间设置为 TimeSpan 类型的参数,可以根据需要进行调整。 使用时,可以创建 RedisCache 对象,并调用 SetData 方法将数据保存到 Redis 中,然后调用 GetData 方法从 Redis 中获取数据: ```csharp var redis = new RedisCache("localhost"); var data = GetDataFromDatabase(); // 从数据库中获取数据 redis.SetData("mykey", data, TimeSpan.FromMinutes(10)); // 将数据保存到 Redis 中,过期时间为 10 分钟 var cachedData = redis.GetData<MyData>("mykey"); // 从 Redis 中获取数据 ``` 需要注意的是,StackExchange.Redis 库支持异步操作,可以使用异步方法提高性能。此外,需要确保 Redis 服务器已经正确配置并运行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值