工具方法笔记

11 篇文章 0 订阅
5 篇文章 0 订阅

1.Java工具类

1.NanoId

import java.security.SecureRandom;
import java.util.Random;

/**
 * @description: NanoId生成唯一ID
 * @create: 2022-05-23 13:38
 */
public class NanoIdUtils {
    public static final SecureRandom DEFAULT_NUMBER_GENERATOR = new SecureRandom();
    public static final char[] DEFAULT_ALPHABET = "_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    public static final int DEFAULT_SIZE = 21;

    public static String randomNanoId() {
        return randomNanoId(DEFAULT_NUMBER_GENERATOR, DEFAULT_ALPHABET, 21);
    }

    public static String randomNanoId(int size) {
        return randomNanoId(DEFAULT_NUMBER_GENERATOR, DEFAULT_ALPHABET, size);
    }

    public static String randomNanoId(Random random, char[] alphabet, int size) {
        if (random == null) {
            throw new IllegalArgumentException("random cannot be null.");
        } else if (alphabet == null) {
            throw new IllegalArgumentException("alphabet cannot be null.");
        } else if (alphabet.length != 0 && alphabet.length < 256) {
            if (size <= 0) {
                throw new IllegalArgumentException("size must be greater than zero.");
            } else {
                int mask = (2 << (int)Math.floor(Math.log((double)(alphabet.length - 1)) / Math.log(2.0D))) - 1;
                int step = (int)Math.ceil(1.6D * (double)mask * (double)size / (double)alphabet.length);
                StringBuilder idBuilder = new StringBuilder();

                while(true) {
                    byte[] bytes = new byte[step];
                    random.nextBytes(bytes);

                    for(int i = 0; i < step; ++i) {
                        int alphabetIndex = bytes[i] & mask;
                        if (alphabetIndex < alphabet.length) {
                            idBuilder.append(alphabet[alphabetIndex]);
                            if (idBuilder.length() == size) {
                                return idBuilder.toString();
                            }
                        }
                    }
                }
            }
        } else {
            throw new IllegalArgumentException("alphabet must contain between 1 and 255 symbols.");
        }
    }

}

2.DateUtils

package com.ruoyi.common.core.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 格式化日期
     *
     * @param date 日期对象
     * @return String 日期字符串
     */
    public static String formatDate(Date date) {
        SimpleDateFormat f = new SimpleDateFormat(YYYY_MM_DD);
        String sDate = f.format(date);
        return sDate;
    }

    public static String formatDate(Date date, String format) {
        SimpleDateFormat f = new SimpleDateFormat(format);
        String sDate = f.format(date);
        return sDate;
    }

    /**
     * 获取当年的第一天
     *
     * @return
     */
    public static Date getCurrYearFirst() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearFirst(currentYear);
    }

    /**
     * 获取当年的最后一天
     *
     * @return
     */
    public static Date getCurrYearLast() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearLast(currentYear);
    }

    /**
     * 获取某年第一天日期
     *
     * @param year 年份
     * @return Date
     */
    public static Date getYearFirst(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }

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

        return currYearLast;
    }

    /*
     * 转换日期
     * */
    public static Date strToDate(String dt, String format) {
        DateFormat format2 = new SimpleDateFormat(format);
        Date d = null;
        try {
            d = format2.parse(dt);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return d;
    }

    /**
     * 得到当前时间
     *
     * @param formate 格式
     * @return
     */
    public static String getCurrentDate(String formate) {
        return formatDate(new Date(), formate);
    }

    /**
     * 获取本周的第一天
     *
     * @return String
     **/
    public static String getWeekStart() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.WEEK_OF_MONTH, 0);
        cal.set(Calendar.DAY_OF_WEEK, 2);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }

    /**
     * 获取本周的最后一天
     *
     * @return String
     **/
    public static String getWeekEnd() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, cal.getActualMaximum(Calendar.DAY_OF_WEEK));
        cal.add(Calendar.DAY_OF_WEEK, 1);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }

    /**
     * 获取本月第一天
     *
     * @return String
     **/
    public static String getMonthStart() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }

    /**
     * 获取本月最后一天
     *
     * @return String
     **/
    public static String getMonthEnd() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }

    public static void main(String[] args) {
        System.out.println(getWeekStart());
        System.out.println(getWeekEnd());
        System.out.println("=======本周========");
        System.out.println(getMonthStart());
        System.out.println(getMonthEnd());
        System.out.println("=======本月========");
        System.out.println(formatDate(getCurrYearFirst()));
        System.out.println(formatDate(getCurrYearLast()));
        System.out.println("=======本年========");
    }


    /**
     * 计算两个天数差
     */
    public static long getDaysDifference(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        return diff / nd;
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 返回当前时间的单个时间类型
     *
     * @param type 1:年;2:月;3:日;
     * @return int
     */
    public static int singleDate(int type) {
        Calendar calendar = Calendar.getInstance();
        switch (type) {
            case 1:
                return calendar.get(Calendar.YEAR);
            case 2:
                return calendar.get(Calendar.MONTH) + 1;
            case 3:
                return calendar.get(Calendar.DATE);
            default:
                return 0;
        }
    }


    /**
     * 获取月份的起始天/最后一天
     *
     * @param direction 方向 (1:上个月;2:本月;3:下个月;)
     * @param startEnd 始/末  (1:月份第一天;2:月份最后一天)
     * @return 返回 yyyy-MM-dd 格式的日期
     */
    public static String getFirstDayMonth(int direction, int startEnd) throws ParseException {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;

        month = direction == 1 ? (month - 1) : direction == 3 ? (month + 1) : month;
        StringBuilder sb = new StringBuilder();
        if (month < 1) {
            sb.append(year - 1).append("-12");
        } else if (month > 12) {
            sb.append(year + 1).append("-01");
        } else {
            sb.append(year).append("-").append(month < 10 ? "0" + month : month);
        }

        sb.append("-01");
        if (startEnd == 2) {
            Calendar c = Calendar.getInstance();
            c.setTime(new SimpleDateFormat(YYYY_MM_DD).parse(sb.toString()));
            c.add(Calendar.MONTH, 0);
            c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE));
            DateFormat format = new SimpleDateFormat(YYYY_MM_DD);
            return format.format(c.getTime());
        }
        return sb.toString();
    }

    /**
     * 获取指定日期的月份
     *
     * @param s 日期
     * @return 月份
     */
    public static int getSpecifyDateMonth(String s) {
        try {
            Date date = new SimpleDateFormat(YYYY_MM_DD).parse(s);
            Calendar now = Calendar.getInstance();
            now.setTime(date);
            return now.get(Calendar.MONTH) + 1;
        } catch (ParseException e) {
            return 0;
        }
    }

    /**
     * 判断指定时间是否包含在指定日期区间
     *
     * @param time1
     * @param time2
     * @return boolean
     * @author Acechengui
     */
    public static boolean isSection(Date thistime, String time1, String time2) throws ParseException {
        //格式化
        SimpleDateFormat sim = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        String s = sim.format(thistime);
        //把string类型的转换为long类型
        long l = sim.parse(s).getTime();
        //区间
        long start = sim.parse(time1).getTime();
        long end = sim.parse(time2).getTime();
        return l > start && l < end;
    }

    /**
     * 计算两个时间的小时差
     */
    public static long getDatehour(String beginTime, String endTime) {
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date begin = dfs.parse(beginTime);
            Date end = dfs.parse(endTime);
            long between = (end.getTime() - begin.getTime())/1000;
            return between/3600;
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 流程完成时间处理
     *
     * @param ms 参数
     */
    public static String getProcessCompletionTime(long ms) {
        long day = ms / (24 * 60 * 60 * 1000);
        long hour = (ms / (60 * 60 * 1000) - day * 24);
        long minute = ((ms / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long second = (ms / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60);

        if (day > 0) {
            return day + "天" + hour + "小时" + minute + "分钟";
        }
        if (hour > 0) {
            return hour + "小时" + minute + "分钟";
        }
        if (minute > 0) {
            return minute + "分钟";
        }
        if (second > 0) {
            return second + "秒";
        } else {
            return 0 + "秒";
        }
    }

    /**
     获取昨天日期
     */
    public Map<String, Integer> productionDate() {
        Map<String, Integer> pram = new HashMap<>();
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int date = calendar.get(Calendar.DATE);

        //如果是月初的话则返回上个月末的日期
        //否则返回昨天的日期
        if (date == 1) {
            month = month == 1 ? 12 : month - 1;
            switch (month) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    date = 31;
                    break;
                case 2:
                    if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
                        date = 29;
                    } else {
                        date = 28;
                    }
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    date = 30;
                    break;
                default:
                    break;
            }
            if (month == 12 && date == 31) {
                year = year - 1;
            }
        } else {
            date = date - 1;
        }

        pram.put("year", year);
        pram.put("month", month);
        pram.put("date", date);
        return pram;
    }
}

3.ServletUtils

/**
 * 客户端工具类
 *
 * @author 芋道源码
 */
public class ServletUtils {

    /**
     * 返回 JSON 字符串
     *
     * @param response 响应
     * @param object 对象,会序列化成 JSON 字符串
     */
    @SuppressWarnings("deprecation") // 必须使用 APPLICATION_JSON_UTF8_VALUE,否则会乱码
    public static void writeJSON(HttpServletResponse response, Object object) {
        String content = JsonUtils.toJsonString(object);
        ServletUtil.write(response, content, MediaType.APPLICATION_JSON_UTF8_VALUE);
    }

    /**
     * 返回附件
     *
     * @param response 响应
     * @param filename 文件名
     * @param content 附件内容
     * @throws IOException
     */
    public static void writeAttachment(HttpServletResponse response, String filename, byte[] content) throws IOException {
        // 设置 header 和 contentType
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        // 输出附件
        IoUtil.write(response.getOutputStream(), false, content);
    }

    /**
     * @param request 请求
     * @return ua
     */
    public static String getUserAgent(HttpServletRequest request) {
        String ua = request.getHeader("User-Agent");
        return ua != null ? ua : "";
    }

    /**
     * 获得请求
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (!(requestAttributes instanceof ServletRequestAttributes)) {
            return null;
        }
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    public static String getUserAgent() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        return getUserAgent(request);
    }

    public static String getClientIP() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        return ServletUtil.getClientIP(request);
    }

    public static boolean isJsonRequest(ServletRequest request) {
        return StrUtil.startWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE);
    }

}

2.Vue组件

1.初始化时间

初始化一周之内时间

//初始化时间
    initDate(){
      var sTm = this.$moment().add(-7, 'days').format('YYYY-MM-DD')
      var eTm = this.$moment().format('YYYY-MM-DD')
      this.daterangeTm[0]=sTm;
      this.daterangeTm[1]=eTm;
      this.queryParams.tm=sTm+' - '+eTm;
    },

2.图例组件

MapLegend.vue 

<template>
  <div class="MapLegend" :style="panel.id==0?'right:890px':panel.id==1?'right:1250px':'right:870px;bottom:120px'"
    v-show="panel.id!=3&&2">
    <div v-for="item in stList" :key="item.id">
      <img :src="item.icon" alt=""> <span>{{item.name}}</span>
    </div>
  </div>
</template>

<script>
import { ref } from '@vue/reactivity';
import { computed } from 'vue-demi';
import { useCounterStore } from '@/stores/counter'
export default {
  name: "MapLegend",
  props: {

  },
  setup () {
    const stList = ref([
      {
        id: 0,
        name: '雨量站',
        icon: require("../assets/img/stNm.png")
      },
      {
        id: 1,
        name: '河道站',
        icon: require("../assets/img/hdIcon.png")
      },
      {
        id: 2,
        name: '水库站',
        icon: require("../assets/img/skIcon.png")
      },
      {
        id: 3,
        name: '视频站',
        icon: require("../assets/img/spIcon.png")
      }
    ])
    const store = useCounterStore()


    return {
      panel: computed(() => store.panel),

      /* 根据标题id确定标注 */
      stList: computed(() => {
        let List = stList.value
        store.panel.id == (0 || 2) ? List : List = [
          {
            id: 0,
            name: '河道站',
            icon: require("../assets/img/hdIcon.png")
          },
          {
            id: 1,
            name: '水库站',
            icon: require("../assets/img/skIcon.png")
          },
          {
            id: 2,
            name: '雨量站',
            icon: require("../assets/img/stNm.png")
          },
          {
            id: 3,
            name: '视频站',
            icon: require("../assets/img/spIcon.png")
          }
        ]
        return List
      }),
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.MapLegend {
  //   width: 112px;
  //   height: 180px;
  background: rgba(0, 0, 0, 0.36);
  position: absolute;
  z-index: 2;
  bottom: 40px;
  //   right: 890px;
  padding: 20px 20px 0 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  color: #fff;
  font-size: 14px;

  div {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    img {
      display: inline-block;
      margin-right: 5px;
    }
  }
}
</style>

HomeView.vue

<template>
    <div>
        <MapLegend />
    </div>
</template>
<script>
    import drawMixin from "../utils/drawMixin";
    import MapLegend from "@/components/MapLegend.vue";
    export default {
      mixins: [drawMixin], //页面自适应
      name: "HomeView",
      components: {
        MapLegend
  },
</script>

utils/drawMixin.js

// 屏幕适配 mixin 函数

// * 默认缩放值
const scale = {
    width: '1',
    height: '1',
}

// * 设计稿尺寸(px)
const baseWidth = 3840
const baseHeight = 1080

// * 需保持的比例(默认1.77778)
const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5))

export default {
    data () {
        return {
            // * 定时函数
            drawTiming: null
        }
    },
    mounted () {
        this.calcRate()
        window.addEventListener('resize', this.resize)
    },
    beforeDestroy () {
        window.removeEventListener('resize', this.resize)
    },
    methods: {
        calcRate () {
            const appRef = this.$refs["appRef"]
            if (!appRef) return
            // 当前宽高比
            const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5))
            if (appRef) {
                if (currentRate > baseProportion) {
                    // 表示更宽
                    scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5)
                    scale.height = (window.innerHeight / baseHeight).toFixed(5)
                    appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
                } else {
                    // 表示更高
                    scale.height = ((window.innerWidth / baseProportion) / baseHeight).toFixed(5)
                    scale.width = (window.innerWidth / baseWidth).toFixed(5)
                    appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
                }
            }
        },
        resize () {
            clearTimeout(this.drawTiming)
            this.drawTiming = setTimeout(() => {
                this.calcRate()
            }, 200)
        }
    },
}

3.Java组件

1.树工具类

TreeNode

@Data
public class TreeNode<T extends TreeNode> {
    protected Integer id;
    protected Integer pId;
    protected List<T> children = new ArrayList<T>();

    public void add(T node) {
        children.add(node);
    }
}

TreeUtil

@UtilityClass
public class TreeUtil {
    /**
           * 两层循环实现建树
           *
           * @param treeNodes 传入的树节点列表
           * @return
           */
      public <T extends TreeNode> List<T> bulid(List<T> treeNodes, Object root) {

                 List<T> trees = new ArrayList<>();

                 for (T treeNode : treeNodes) {

                         if (root.equals(treeNode.getPId())) {
                                 trees.add(treeNode);
                             }

                         for (T it : treeNodes) {
                                 if (it.getPId() == treeNode.getId()) {
                                         if (treeNode.getChildren() == null) {
                                                 treeNode.setChildren(new ArrayList<>());
                                             }
                                         treeNode.add(it);
                                     }
                             }
                     }
                 return trees;
             }

    /**
      * 使用递归方法建树
       *
      * @param treeNodes
       * @return
       */
             public <T extends TreeNode> List<T> buildByRecursive(List<T> treeNodes, Object root) {
                 List<T> trees = new ArrayList<T>();
                 for (T treeNode : treeNodes) {
                         if (root.equals(treeNode.getPId())) {
                                trees.add(findChildren(treeNode, treeNodes));
                             }
                     }
                 return trees;
             }

             /**
       * 递归查找子节点
       *
       * @param treeNodes
       * @return
       */
             public <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes) {
                 for (T it : treeNodes) {
                         if (treeNode.getId() == it.getPId()) {
                                 if (treeNode.getChildren() == null) {
                                         treeNode.setChildren(new ArrayList<>());
                                     }
                                 treeNode.add(findChildren(it, treeNodes));
                             }
                     }
                 return treeNode;
            }
}

4.JS工具类

1.部门树形结构

getArryByPid(list, pid) {
      return list.filter((item) => {
        return item.pid == pid;
      });
    },
    digui(list, pid) {
      const arr = [];
      const resList = this.getArryByPid(list, pid);
      resList.forEach((item) => {
        item.children = this.digui(list, item.id);
        arr.push(item);
      });
      return arr;
    },
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then((response) => {
        this.deptList = this.handleTree(response.data, "deptId");
        this.loading = false;

        const meList = [];
        response.data.forEach((item) => {
          meList.push({
            id: item.deptId,
            label: item.deptName,
            name: item.deptName,
            pid: item.parentId,
          });
        });
        const arr0 = this.getArryByPid(meList, 0);
        arr0.forEach((item) => {
          item.children = this.digui(meList, item.id);
        });
        // console.log(arr0);
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
      };
    },

2.日期工具类

地址:JS日期格式化转换方法 - 腾讯云开发者社区-腾讯云

Date.prototype.format = function(fmt) { 
     var o = { 
        "M+" : this.getMonth()+1,                 //月份 
        "d+" : this.getDate(),                    //日 
        "h+" : this.getHours(),                   //小时 
        "m+" : this.getMinutes(),                 //分 
        "s+" : this.getSeconds(),                 //秒 
        "q+" : Math.floor((this.getMonth()+3)/3), //季度 
        "S"  : this.getMilliseconds()             //毫秒 
    }; 
    if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
    }
     for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
         }
     }
    return fmt; 
}        
var time1 = new Date().format("yyyy-MM-dd hh:mm:ss");
console.log(time1);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值