UserTools.java 1.71 KB
package com.objecteye.utils;

import com.alibaba.fastjson.JSONArray;
import com.objecteye.entity.PageResult;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UserTools {

    public static JSONArray getJSONArrayByList(List list) {
        JSONArray jsonArray = new JSONArray();
        if (list == null || list.isEmpty()) {
            return jsonArray;
        }
        jsonArray.addAll(list);
        return jsonArray;
    }

    public static String nowToDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }

    /**
     * 统一手动分页
     *
     * @param baseList    原始数据集合
     * @param currentpage 页码
     * @param pagevolume  页面容量
     * @return 结果集
     */
    public static PageResult makePageResultByBaseList(List<?> baseList, Integer currentpage, Integer pagevolume) {
        // 总页数
        int pageTotal = (baseList.size() / pagevolume) + ((baseList.size() % pagevolume > 0) ? 1 : 0);

        int fromIndex = (currentpage - 1) * pagevolume;
        int toIndex;
        if (currentpage == pageTotal) {
            toIndex = baseList.size();
        } else if (pageTotal == 0) {
            return new PageResult<>(pageTotal, new ArrayList<>());
        } else {
            toIndex = currentpage * pagevolume;
            if (toIndex > baseList.size()) {
                toIndex = baseList.size();
            }
            if (fromIndex >= toIndex) {
                return new PageResult<>(pageTotal, new ArrayList<>());
            }
        }

        return new PageResult<>(pageTotal, baseList.subList(fromIndex, toIndex));
    }
}