第三方接口获取数据存入本地数据库(SQLSERVER)方法

第三方接口获取数据存入本地数据库(SQLSERVER)方法

一、操作的json格式

解决SQLSERVER大批量插入数据库时报该服务器最多支持2100个参数的解决方法

本例借用旺店通标准API进行讲解怎么把第三方接口数据存入本地

json格式为标注格式,格式如下:
{
“code”: 0,
“message”: “succeed”,
“total_count”: 19,
“stockout_list”: [{
“stockout_id”: “87562”,
“order_no”: “CK2018051823”,
“src_order_no”: “JY201805180021”,
“warehouse_no”: “api_test”,
“consign_time”: “2018-05-18 18:25:04”,
“status”: “95”,
“order_type”: “1”,
“goods_count”: “1.0000”,
“goods_total_amount”: “0.0100”,
“goods_total_cost”: “0.0000”,
“post_fee”: “0.0000”,
“logistics_no”: “58745896584”,
“package_fee”: “0.0000”,
“receiver_name”: “测试”,
“receiver_country”: “0”,
“receiver_province”: “福建”,
“receiver_city”: “厦门市”,
“receiver_district”: “思明区”,
“receiver_address”: “吕岭服务处 双浦西里8号 1103”,
“receiver_mobile”: “18750257319”,
“receiver_telno”: “18750257319”,
“receiver_zip”: “”,
“remark”: “”,
“weight”: “0.0000”,
“stockout_reason”: “”,
“subtype”: “”,
“outer_no”: “”,
“operator_name”: “bsd2test”,
“logistics_type”: “35”,
“logistics_code”: “YS001”,
“logistics_name”: “优速快递”,
“bad_reason”: “0”,
“receiver_dtb”: “”,
“print_remark”: “aqh^udruBJ3109140932”,
“paid”: “0.0100”,
“refund_status”: “0”,
“trade_type”: “1”,
“salesman_no”: “SYSTEM”,
“fullname”: “系统”,
“trade_status”: “95”,
“warehouse_name”: “API公共测试”,
“block_reason”: “0”,
“trade_no”: “JY201805180021”,
“src_trade_no”: “HP201805181820181147714”,
“nick_name”: “MOB18750257319”,
“customer_no”: “KH201805150005”,
“customer_name”: “测试”,
“trade_time”: “2018-05-18 18:20:18”,
“pay_time”: “2018-05-18 18:20:39”,
“flag_name”: null,
“post_amount”: “0.0000”,
“id_card_type”: “0”,
“id_card”: “”,
“receiver_area”: “福建 厦门市 思明区”,
“shop_name”: “API公共测试”,
“shop_no”: “api_test”,
“shop_remark”: “公共测试店铺,禁止修改,发现将停掉测试环境使用权限,店铺内数据为全体测试卖家使用,如果要单独使用请自己创建店铺仓库!!!”,
“modified”: “2018-05-18 18:25:04”,
“buyer_message”: “”,
“cs_remark”: “极速达”,
“invoice_type”: “1”,
“invoice_title”: “”,
“invoice_content”: “”,
“invoice_id”: “0”,
“cod_amount”: “0.0000”,
“delivery_term”: “1”,
“platform_id”: “127”,
“trade_id”: “37858”,
“employee_no”: “bsd2test”,
“discount”: “0.0000”,
“src_tids”: “HP201805181820181147714”,
“tax”: “0.0000”,
“tax_rate”: “0.0000”,
“currency”: “”,
“created”: “2018-05-18 18:23:21”,
“stock_check_time”: “2018-05-18 18:23:30”,
“order_type_name”: “销售订单”,
“receiver_province_code”: “0”,
“receiver_city_code”: “0”,
“receiver_district_code”: “0”,
“details_list”: [{
“rec_id”: “79829”,
“stockout_id”: “87562”,
“spec_no”: “1013000220”,
“goods_count”: “1.0000”,
“total_amount”: “0.0100”,
“paid”: “0.0100”,
“sell_price”: “0.0100”,
“remark”: “”,
“goods_name”: “ERP普通测试商品2”,
“goods_no”: “lztestyj02”,
“brand_no”: “BRAND”,
“brand_name”: “无”,
“spec_name”: “Deonatulle 药用软石 20g”,
“spec_code”: “”,
“cost_price”: “0.0000”,
“weight”: “0.0000”,
“goods_id”: “2”,
“spec_id”: “133434”,
“prop1”: “”,
“prop2”: “”,
“prop3”: “”,
“prop4”: “”,
“prop5”: “”,
“prop6”: “”,
“platform_id”: “127”,
“refund_status”: “0”,
“market_price”: “0.0100”,
“discount”: “0.0000”,
“share_amount”: “0.0100”,
“tax_rate”: “0.0000”,
“barcode”: “”,
“unit_name”: null,
“sale_order_id”: “45544”,
“share_post”: “0.0000”,
“gift_type”: “0”,
“src_oid”: “HP1095”,
“src_tid”: “HP201805181820181147714”,
“from_mask”: “0”,
“goods_type”: “1”,
“batch_no”: null,
“good_prop1”: “”,
“good_prop2”: “”,
“good_prop3”: “”,
“good_prop4”: “”,
“good_prop5”: “”,
“good_prop6”: “”
}]
}]
}

二、对于获取的json进行操作

此处省略旺店通的方法,有需要可以联系(QQ:1354031513)

try {
//向接口请求,返回的数据
			requestBackResult = client1.execute("http://api.wangdian.cn/openapi2/stockout_order_query_trade.php",
					params1);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//把返回的数据转换成JSON
		JSONObject jsonData = JSONObject.fromObject(requestBackResult);
//		System.out.println(jsonData);
//由于是多层的JSON格式,进行第一层的取值
		JSONArray jsonDataArray = JSONArray.fromObject(jsonData.get("stockout_list"));
		//判断jsonDataArray 是否为空
		if (jsonDataArray == null || jsonDataArray.size() == 0){
			return 0;
		}
		MyLogger.writeInfoLog("-----------------------【" + this.getClass().getName() + ":获取数据条数:"
				+ jsonDataArray.size() + "】-----------------------");
//jsonDataArray.size满足条件插入数据库
		if (jsonDataArray.size() > 0) {
			Integer insert = orderOutService.insert(jsonDataArray);
			System.out.println("一共插入" + insert + "条数据");
		}
        if (jsonDataArray.size() > 0) {
        //第二层数据时进行遍历取值插入数据库,还存在第三层甚至更多就继续在该循环下在循环
			for (int i = 0; i < jsonDataArray.size(); i++) {
				JSONArray details_list = jsonDataArray.getJSONObject(i).getJSONArray("details_list");
				Integer insert = orderOutService.insertDetails(details_list);
				System.out.println("一共插入" + insert + "条数据");
				//for(int j=0;j<detailsI_list.size();j++){
				//	JSONArray xxxx=detailsI_list.getJSONObject(j).getJSONArray("xxxxx");
				//	...............
				//}
			}
        }

以上处理完就可以进入orderOutService里面了

三、OrderOutService

/**
 * 
 */
package com.commons.service;


import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.baseframework.commons.logger.MyLogger;
import com.baseframework.commons.util.date.UtilDate;
import com.baseframework.commons.util.string.UtilString;
import com.commons.mybatis.OrderOutMapper;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author Administrator
 *
 */
@Service
public class OrderOutService {

	@Autowired
	private OrderOutMapper orderOutMapper;

	@Transactional(readOnly = false, rollbackFor = RuntimeException.class)
	public Integer insert(JSONArray dataList) {
		try {
			// 要插入的数据字段
			String[] key = { "stockout_id","order_no","src_order_no","warehouse_no","consign_time","order_type","trade_status","order_type_name","trade_type","subtype","goods_count","goods_total_amount","goods_total_cost","post_fee","logistics_no","package_fee","receiver_name","receiver_country","receiver_province","receiver_city","receiver_district","receiver_address","receiver_mobile","receiver_telno","receiver_zip","weight","logistics_type","logistics_code","logistics_name","print_remark","paid","refund_status","warehouse_name","created","remark","stockout_reason","outer_no","src_trade_no","nick_name","customer_name","customer_no","consign_time","pay_time","status","shop_name","shop_no","cs_remark","flag_name","post_amount","block_reason","delivery_term","cod_amount","receiver_area","shop_remark","modified","platform_id","trade_id","discount","src_tids","currency","stock_check_time","bad_reason"};

			// 数字格式的字段名称
			String[] numberCloumn = {"stockout_id","order_type","trade_status","trade_type","receiver_country","logistics_type","refund_status","status","block_reason","delivery_term","platform_id","trade_id","bad_reason" };

			// 浮点格式的格式的字段名称
			String[] deoubleCloumn = {"goods_count","goods_total_amount","goods_total_cost","post_fee","package_fee","weight","paid","post_amount","cod_amount","discount"};

			// 日期格式的字段名称
			String[] dateCloumn = { "consign_time","created","consign_time","pay_time","modified","stock_check_time" };

			List<Map<String, Object>> valueMapList = new ArrayList<Map<String, Object>>();
			// 将字段转成List集合,方便动态组装SQL
			Map<String, String> cloumnMap = new HashMap<String, String>();
			List<Map<String, String>> cloumnMapList = new ArrayList<Map<String, String>>();

			// 遍历实际数据
			for(int j=0;j<dataList.size();j++){
				JSONObject object = dataList.getJSONObject(j);
				Map<String, Object> valueMap = new HashMap<String, Object>();
				for(int k = 0;k<key.length;k++) {
					if(j==0){
						cloumnMap.put(key[k], key[k]);
					}
					// 判断是否是日期字段
					if (UtilString.useLoop(dateCloumn, key[k])) {
						valueMap.put(key[k], UtilDate.DATE_LONG_FORMAT.parse(object.getString(key[k])));
					} // 判断是否是数字格式
					else if (UtilString.useLoop(numberCloumn, key[k])) {
						String value = UtilString.isNullOrEmptyStr((object.getString(key[k]).replace("null", "")), "0");
						valueMap.put(key[k], Integer.parseInt(value));
					} // 判断是否是浮点格式
					else if (UtilString.useLoop(deoubleCloumn, key[k])) {
						String value = UtilString.isNullOrEmptyStr((object.getString(key[k]).replace("null", "")), "0");
						valueMap.put(key[k], Double.valueOf(value));
					} // 默认
					else {
						valueMap.put(key[k], object.getString(key[k]));
					}
				}
				valueMapList.add(valueMap);

			}
			cloumnMapList.add(cloumnMap);
			//传入的请求具有过多的参数。该服务器支持最多 2100 个参数。
			if (valueMapList != null && valueMapList.size() != 0){
				if (valueMapList.size() < 2000) {
					return orderOutMapper.insert(cloumnMapList, valueMapList);
				} else {
					// 每次插入数据库的数据量
					int preInsertDataCount = 2000;
					// 可遍历的插入数据库的次数
					int insertSqlCount = 0;
					// 总数据条数
					int totalDataCount=valueMapList.size();
					if(totalDataCount%preInsertDataCount==0){
						insertSqlCount=totalDataCount/preInsertDataCount;
					}else
					{
						insertSqlCount=totalDataCount/preInsertDataCount+1;
					}
					for (int i = 0; i < insertSqlCount; i++) {
						int startNumber = i * preInsertDataCount;
//						if (startNumber > 0) {
//							startNumber = startNumber ;
//						}
						int endUnmber = (i + 1) * preInsertDataCount ;
						if (endUnmber > totalDataCount) {
							endUnmber = totalDataCount ;
						}
						List<Map<String, Object>> subListOK = valueMapList.subList(startNumber,endUnmber);
						orderOutMapper.insert(cloumnMapList, subListOK);
					}
//					int len = 30;
//					int size = valueMapList.size();
//					int count = (size + len - 1) / len;
//					for (int i = 0; i < count; i++) {
//						List<Map<String, Object>> subListOK = valueMapList.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
//						return orderOutMapper.insert(cloumnMapList, subListOK);
//					}
				}
			}
		}catch (RuntimeException  ex) {
			MyLogger.writeErrorLog(getClass(),"",ex);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		} catch (ParseException ex) {
			// TODO Auto-generated catch block
			MyLogger.writeErrorLog(getClass(), "", ex);
		}
		return 0;
	}


    @Transactional(readOnly = false, rollbackFor = RuntimeException.class)
    public Integer insertDetails(JSONArray jsonDataDetailsArray) {
		try {
			// 要插入的数据字段
			String[] key = { "rec_id","stockout_id","spec_no","goods_count","sell_price","goods_type","gift_type","goods_name","goods_no","spec_name","spec_code","suite_no","cost_price","total_amount","goods_id","spec_id","weight","remark","paid","refund_status","market_price","discount","share_amount","barcode","sale_order_id","share_post","src_oid","src_tid","from_mask","good_prop1","good_prop2","good_prop3","good_prop4","good_prop5","good_prop6","prop1","prop2","prop3","prop4","prop5","prop6","batch_no","unit_name"};

			// 数字格式的字段名称
			String[] numberCloumn = {"rec_id","stockout_id","goods_type","gift_type","goods_id","spec_id","refund_status","sale_order_id","from_mask" };

			// 浮点格式的格式的字段名称
			String[] deoubleCloumn = {"goods_count","sell_price","cost_price","total_amount","weight","paid","market_price","discount","share_amount","share_post"};

			// 日期格式的字段名称
			String[] dateCloumn = { };

			List<Map<String, Object>> valueMapList = new ArrayList<Map<String, Object>>();
			// 将字段转成List集合,方便动态组装SQL
			Map<String, String> cloumnMap = new HashMap<String, String>();
			List<Map<String, String>> cloumnMapList = new ArrayList<Map<String, String>>();

			// 遍历实际数据
			for(int j=0;j<jsonDataDetailsArray.size();j++){
				JSONObject object = jsonDataDetailsArray.getJSONObject(j);
				Map<String, Object> valueMap = new HashMap<String, Object>();
				for(int k = 0;k<key.length;k++) {
					if(j==0){
						cloumnMap.put(key[k], key[k]);
					}
					// 判断是否是日期字段
					if (UtilString.useLoop(dateCloumn, key[k])) {
						valueMap.put(key[k], UtilDate.DATE_LONG_FORMAT.parse(object.getString(key[k])));
					} // 判断是否是数字格式
					else if (UtilString.useLoop(numberCloumn, key[k])) {
						String value = UtilString.isNullOrEmptyStr((object.getString(key[k]).replace("null", "")), "0");
						valueMap.put(key[k], Integer.parseInt(value));
					} // 判断是否是浮点格式
					else if (UtilString.useLoop(deoubleCloumn, key[k])) {
						String value = UtilString.isNullOrEmptyStr((object.getString(key[k]).replace("null", "")), "0");
						valueMap.put(key[k], Double.valueOf(value));
					} // 默认处理
					else {
						valueMap.put(key[k], object.getString(key[k]).replace("null", "0"));
					}
				}
				valueMapList.add(valueMap);

			}
			cloumnMapList.add(cloumnMap);
			//传入的请求具有过多的参数。该服务器支持最多 2100 个参数。
			if (valueMapList != null && valueMapList.size() != 0){
				if (valueMapList.size() < 2000) {
					return orderOutMapper.insertDetails(cloumnMapList, valueMapList);
				} else {
					// 每次插入数据库的数据量
					int preInsertDataCount = 2000;
					// 可遍历的插入数据库的次数
					int insertSqlCount = 0;
					// 总数据条数
					int totalDataCount=valueMapList.size();
					if(totalDataCount%preInsertDataCount==0){
						insertSqlCount=totalDataCount/preInsertDataCount;
					}else
					{
						insertSqlCount=totalDataCount/preInsertDataCount+1;
					}
					for (int i = 0; i < insertSqlCount; i++) {
						int startNumber = i * preInsertDataCount;
//						if (startNumber > 0) {
//							startNumber = startNumber ;
//						}
						int endUnmber = (i + 1) * preInsertDataCount ;
						if (endUnmber > totalDataCount) {
							endUnmber = totalDataCount ;
						}
						List<Map<String, Object>> subListOK = valueMapList.subList(startNumber,endUnmber);
						orderOutMapper.insertDetails(cloumnMapList, subListOK);
					}
//					int len = 30;
//					int size = valueMapList.size();
//					int count = (size + len - 1) / len;
//					for (int i = 0; i < count; i++) {
//						List<Map<String, Object>> subListOK = valueMapList.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
//						return orderOutMapper.insertDetails(cloumnMapList, subListOK);
//					}
				}
			}
		}catch (RuntimeException  ex) {
			MyLogger.writeErrorLog(getClass(),"",ex);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		} catch (ParseException ex) {
			// TODO Auto-generated catch block
			MyLogger.writeErrorLog(getClass(), "", ex);
		}
		return 0;

    }
}

因为后面使用的是占位符的方式,需要对数据类型的判断
OrderOutService使用到的工具类,先建立UtilString和UtilDate的类(可以直接复制粘贴,不用修改任何的代码)

UtilString

package com.baseframework.commons.util.string;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符格式的处理工具类,提供判断字符长度,为空,编码,加密等方法 
 * 
 * @author 
 * @version 1.0
 */
public class UtilString {

    /**
     * 判断字符是不是数字(并且为整整数)
     * 
     * @param str
     * @return
     */
    public static boolean isNumAndGreaterThanZero(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (str == null || str.trim().equals("")) {
            return false;
        } else {
            if (!isNum.matches()) {
                return false;
            } else {
                if (Integer.parseInt(str) >= 0) {
                    return true;
                } else {
                    return false;
                }
            }
        }
    }

    /**
     * 判断一个字符串是否是所有空格
     * 
     * @param s
     * @return
     */
    public static boolean removeAllSpace(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return isNull(dest);
    }

    /**
     * 过滤一个字符串中的所有空格
     * 
     * @param s
     * @return
     */
    public static String removeSpace(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;

    }

    /**
     * 判断字符是否为空
     * 
     * @param s
     * @return
     */
    public static boolean isNull(Object s) {
        if (s == null || removeSpace(s.toString()).equals(""))
            return true;
        else {
            return false;
        }
    }

    /**
     * 判断是否为空并返回空字符串
     * 
     * @param s
     * @return
     */
    public static String emptyString(Object s) {
        if (s == null || removeSpace(s.toString()).equals(""))
            return "";
        else {
            return removeSpace(s.toString());
        }
    }

    /**
     * 判断是否为空并返回,如果为空 则返回 null 对象
     * 
     * @param s
     * @return
     */
    public static String nullString(Object s) {
        if (s == null || removeSpace(s.toString()).equals(""))
            return null;
        else {
            return removeSpace(s.toString());
        }
    }

    /**
     * 判断输入是否为空,为空返回指定的默认值,否则返回原值
     * 
     * @Title: isNullOrEmptyStr
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param s
     * @param replaceReturn
     * @return String
     * @throws
     */
    public static String isNullOrEmptyStr(Object s, Object replaceReturn) {
        if (s == null || removeSpace(s.toString()).equals(""))
            return removeSpace(replaceReturn.toString());
        else {
            return removeSpace(s.toString());
        }
    }

    /**
     * 用于sql语句的字符串中单引号的过滤, 将单个单引号替换成双个单引号
     * 
     * @param s 要过滤的字符串
     * @return 返回过滤后的字符串
     */
    public static String getSqlStr(Object s) {
        if (s == null) {
            return "''";
        } else {
            String str = s.toString();
            return "'" + str.replaceAll("'", "''") + "'";
        }
    }

    /**
     * 加密字符串
     * 
     * @param csinput被加密的字符串
     * @return 返回通过MD5加密后的字符串
     */
    public static String transferMD5(String csinput, int len) {
        byte[] b, b2;
        StringBuffer buf;
        String csreturn = null;
        try {
            b = csinput.getBytes("iso-8859-1");
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(b);
            b2 = md.digest();
            buf = new StringBuffer(b2.length * 2);
            for (int nLoopindex = 0; nLoopindex < b2.length; nLoopindex++) {
                if ((b2[nLoopindex] & 0xff) < 0x10) {
                    buf.append("0");
                }
                buf.append(Long.toString(b2[nLoopindex] & 0xff, len));
            }
            csreturn = new String(buf);
        } catch (Exception e) {
            csreturn = null;
        }
        return csreturn;
    }

    /**
     * 判断指定字符串的编码集
     * 
     * @param str要判断的字符串
     * @return 指定字符串的编码集。可能存在指定字符串在多种字符集下显示正常,此字符串将不能判断它的真正字符集
     */
    public static String getEncoding(String str) {
        /*
         * 将指定的字符串通过转码后如果还能和转码前的字符串匹配 将认为该字符串为转码的字符集
         */
        String encode = "UTF-8";
        // UTF-8的字符集判断
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s = encode;
                return s;
            }
        } catch (Exception exception) {
        }
        // GB2312的字符集判断
        encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }
        // ISO-8859-1的字符集判断
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }
        // GBK的字符集判断
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        // 都不符合时返回
        return "";
    }

    /**
     * 将指定的字符串转码为UTF-8的编码格式
     * 
     * @param str -要转换的字符串
     * @return 返回转码后的字符串
     */
    public static String getUTF(String str) {
        try {
            // 得到指定字符串的编码集
            String encode = getEncoding(str);
            // 根据指定字符串的编码集得到该字符串的字节数组
            byte[] b = str.getBytes(encode);
            // 返回UTF-8编码的字符串
            return new String(b, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            return str;
        }
    }

    /**
     * 将指定的字符串转码为UTF-8的编码格式
     * 
     * @param str -要转换的字符串
     * @return 返回转码后的字符串
     */
    public static String getGBK(String str, String newEncode) {
        try {
            // 得到指定字符串的编码集
            String encode = getEncoding(str);
            // 根据指定字符串的编码集得到该字符串的字节数组
            byte[] b = str.getBytes(encode);
            // 返回UTF-8编码的字符串
            return new String(b, newEncode);
        } catch (UnsupportedEncodingException e1) {
            return str;
        }
    }

    /**
     * 判断字符长度是否超过设定长度
     * 
     * @param str 字符串
     * @param offset 设定的长度,中文汉字乘以2
     * @return
     */
    public static boolean judegeStrLength(String str, int offset) {
        if (str.length() <= offset) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * @param text
     * @param length
     * @param sign
     * @return
     */
    public static String subStringText(String text, int length, String sign) {
        if (text.length() <= length) {
            return text;
        } else {
            text = text.substring(0, length).toString() + sign;
            return text;
        }
    }

    /**
     * 按照字节数来截取长度
     * 
     * @param str 字符串
     * @param a 要截取的长度 汉字是2个字节,其他1个字节
     * @return
     */
    public static String interceptStr(String str, int len, String sign) {
        String temp = "";
        int k = 0;
        for (int i = 0; i < str.length(); i++) {
            byte[] b = (str.charAt(i) + "").getBytes(); // 每循环一次,将str里的值放入byte数组
            k = k + b.length;
            if (k > len) { // 如果数组长度大于6,随机跳出循环
                break;
            }
            temp = temp + str.charAt(i); // 拼接新字符串
        }
        if (k > len && sign != null) {
            temp += sign;
        }
        return temp;
    }

    /**
     * 将指定的信息写入指定的文件中
     * 
     * @param fileName -要写入的文件路径
     * @param message -要写入的信息
     * @return 是否写入成功
     */
    public static boolean writeLog(String fileName, String message) {
        OutputStreamWriter fout = null;
        String errorLog = getDateStr("yyyy-MM-dd") + ".log";

        try {
            // 根据要写入的文件路径和“UTF-8”编码创建一个文件输出流
            fout = new OutputStreamWriter(new FileOutputStream(fileName + errorLog, true), "UTF-8");
            // 在写入信息后换行
            fout.write(message);
            return true;
        } catch (Exception e) {
        } finally {
            /*
             * 刷新和关闭输出流
             */
            try {
                if (fout != null) {
                    fout.flush();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                if (fout != null) {
                    fout.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 将指定的信息写入指定的文件中
     * 
     * @param fileName -要写入的文件路径
     * @param message -要写入的信息
     * @return 是否写入成功
     */
    public static boolean writeSql(String fileName, String message) {
        OutputStreamWriter fout = null;
        String errorLog = getDateStr("yyyy-MM-dd") + ".sql";

        try {
            // 根据要写入的文件路径和“UTF-8”编码创建一个文件输出流
            fout = new OutputStreamWriter(new FileOutputStream(fileName + errorLog, true), "UTF-8");
            // 在写入信息后换行
            fout.write(message);
            return true;
        } catch (Exception e) {
        } finally {
            /*
             * 刷新和关闭输出流
             */
            try {
                if (fout != null) {
                    fout.flush();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                if (fout != null) {
                    fout.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 根据格式获取当前日期
     * 
     * @param format 日期格式
     * @return
     */
    public static String getDateStr(String format) {
        String strDate = "";
        java.util.Date dDate = new java.util.Date();
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(format);
        strDate = formatter.format(dDate);
        return strDate;
    }

    /**
     * @param s
     * @return 去掉标记
     */
    public static String outTag(final String s) {
        return s.replaceAll("<.*?>", "");
    }

    /**
     * 将字符串遍历为list
     * 
     * @param cids
     * @return
     */
    public static List<String> composeList(String str, String px) {
        List<String> list = new ArrayList<String>();
        for (String c : str.split(px)) {
            list.add(c);
        }
        return list;
    }

    /**
     * 将字符串遍历为list
     * 
     * @param cids
     * @return
     */
    public static List<Integer> composeListInteger(String str, String px) {
        List<Integer> list = new ArrayList<Integer>();
        for (String c : str.split(px)) {
            list.add(Integer.parseInt(c));
        }
        return list;
    }

    /**
     * 右补位,左对齐
     * 
     * @param oriStr 原字符串
     * @param len 目标字符串长度
     * @param alexin 补位字符
     * @return 目标字符串
     */
    public static String padRight(String oriStr, int len, char alexin) {
        String str = "";
        int strlen = oriStr.length();
        if (strlen < len) {
            for (int i = 0; i < len - strlen; i++) {
                str = str + alexin;
            }
        }
        str = str + oriStr;
        return str;
    }

    /**
     * 左补位,右对齐
     * 
     * @param oriStr 原字符串
     * @param len 目标字符串长度
     * @param alexin 补位字符
     * @return 目标字符串
     */
    public static String padLeft(String oriStr, int len, char alexin) {
        String str = "";
        int strlen = oriStr.length();
        if (strlen < len) {
            for (int i = 0; i < len - strlen; i++) {
                str = str + alexin;
            }
        }
        str = oriStr + str;
        return str;
    }

    public static String to24Hours(Integer time) {
        if (time <= 9) {
            return padRight(time + ":00", 5, '0');
        }
        return time + ":00";
    }

    public static boolean useLoop(String[] arr, String targetValue) {
        for (String s : arr) {
            if (s.equals(targetValue))
                return true;
        }
        return false;
    }

    public static void main(String[] args) {
        String[] arr = { "a", "b", "c", "d" };
        System.out.println(useLoop(arr, "e"));
    }
}

UtilDate

package com.baseframework.commons.util.date;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 提供处理与日期相关的各种工具
 * 
 * @author 
 */
public class UtilDate {
    /**
     * 英文简写(默认)如:2010-12-01
     */
    public static String DATE_SHORT_STR = "yyyy-MM-dd";

    /**
     * 英文全称 如:2010-12-01 23:15:06
     */
    public static String DATE_LONG_STR = "yyyy-MM-dd HH:mm:ss";

    /**
     * 精确到毫秒的完整时间 如:yyyy-MM-dd HH:mm:ss.S
     */
    public static String DATE_FULL_STR = "yyyy-MM-dd HH:mm:ss.S";

    /**
     * 精确到毫秒的完整时间 如:yyyy-MM-dd HH:mm:ss.S
     */
    public static String DATE_FULL_TIMESTAMP = "yyyyMMddHHmmss";

    /**
     * 中文简写 如:2010年12月01日
     */
    public static String DATE_SHORT_STR_CN = "yyyy年MM月dd";

    /**
     * 中文全称 如:2010年12月01日 23时15分06秒
     */
    public static String DATE_LONG_STR_CN = "yyyy年MM月dd日  HH时mm分ss秒";

    /**
     * 精确到毫秒的完整中文时间
     */
    public static String FORMAT_FULL_CN = "yyyy年MM月dd日  HH时mm分ss秒SSS毫秒";

    /**
     * 一个以“yyyy-MM-dd”方式格式化日期的对象
     */
    public static final SimpleDateFormat DATE_SHORT_FORMAT = new SimpleDateFormat(DATE_SHORT_STR);

    /**
     * 一个包含日期和时间的格式化日期对象
     */
    public static final SimpleDateFormat DATE_LONG_FORMAT = new SimpleDateFormat(DATE_LONG_STR);

    /**
     * 根据指定的格式化方式将日期格式化为字符串
     * 
     * @param date 要格式化的日期
     * @param format 格式化方式
     * @return 格式化后的日期字符串
     */
    public static String formatDate(Date date, SimpleDateFormat format) {
        return date == null || format == null ? null : format.format(date);
    }

    /**
     * 将指定的日期按默认的“yyyy-MM-dd”方式格式化为字符串
     * 
     * @param date 要格式化的日期
     * @return 格式化后的日期字符串
     */
    public static String formatDate(Date date) {
        return date == null ? null : formatDate(date, DATE_LONG_FORMAT);
    }

    /**
     * 格式化Timestamp格式的时间
     * 
     * @param ts
     * @return
     */
    public static String formatDate(Timestamp ts, String format) {
        String tsStr = "";
        DateFormat sdf = new SimpleDateFormat(format);
        try {
            // 方法一
            tsStr = sdf.format(ts);
            return tsStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 格式化Timestamp格式的时间
     * 
     * @param ts
     * @return
     */
    public static Date formatDate(Timestamp ts) {
        Date date = new Date();
        try {
            date = ts;
            return date;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据指定的格式将日期格式化为字符串
     * 
     * @param date 日期
     * @param format 格式化方式
     * @return 格式化后的日期字符串
     */
    public static String formatDate(Date date, String format) {
        return date == null ? null : new SimpleDateFormat(format).format(date);
    }

    /**
     * 字符串转换成日期
     * 
     * @param str
     * @return date
     */
    public static Date StrToDate(String str) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 改变日期的分钟数
     * 
     * @author:王雪峰
     * @date:2012-3-23 上午09:58:32
     * @Title:DateTools.java
     * @Description:TODO
     * @param date
     * @param count
     * @param add
     * @return
     * @Throws
     */
    public static Date addMinute(Date date, int count) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        if (count != 0) {
            ca.add(Calendar.MINUTE, count);
        }
        date = ca.getTime();
        return date;
    }

    /**
     * 增加天数
     * 
     * @Title: addDay
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param date
     * @param count
     * @return Date
     * @throws
     */
    public static Date addDay(Date date, int count) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        if (count != 0) {
            ca.add(Calendar.DATE, count);
        }
        date = ca.getTime();
        return date;
    }

    /**
     * 增加年数
     * 
     * @Title: addYear
     * @param date
     * @param count
     * @return
     * @throws
     */
    public static Date addYear(Date date, int count) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        if (count != 0) {
            ca.add(Calendar.YEAR, count);
        }
        date = ca.getTime();
        return date;
    }

    /**
     * 获取指定日期的相隔天数
     * 
     * @Title: getNextDay
     * @Description:
     * @param date 指定日期
     * @param days 相隔天数,+为大于,-为小于
     * @return
     * @throws
     */
    public static Date getNextDay(Date date, int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, days);
        date = calendar.getTime();
        return date;
    }

    /**
     * 获取指定日期的相隔天数
     * 
     * @Title: getNextDay
     * @Description:
     * @param date 指定日期
     * @param days 相隔天数,+为大于,-为小于
     * @return
     * @throws
     */
    public static String getNextMonth(Date date, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, month);
        date = calendar.getTime();
        return DATE_LONG_FORMAT.format(date);
    }

    /**
     * 仅比较2个时间的大小,并返回比较结果用户需要的表达
     * 
     * @param starttime 开始时间
     * @param endtime 结束时间
     * @param tresult 开始时间大于结束时间时返回的表达
     * @param fresult 开始时间小于结束时间时返回的表达
     * @return
     * @throws Exception
     */
    public static boolean singleCompareTime(Date starttime, Date endtime) {
        if (endtime.getTime() > starttime.getTime()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 时间间隔
     * 
     * @param starttime
     * @param endtime
     * @return
     */
    public static boolean timeInterval(Date starttime, Date endtime) {
        if (endtime.getTime() > starttime.getTime()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 仅比较2个时间的大小,并返回比较结果用户需要的表达
     * 
     * @param starttime 开始时间
     * @param endtime 结束时间
     * @return 开始时间小于等于结束时间返回true
     * @throws Exception
     */
    public static boolean compareTime(Date starttime, Date endtime) {
        if (starttime.getTime() <= endtime.getTime()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取指定年月天数
     * 
     * @Title: getDaysByYearMonth
     * @Description:
     * @param year
     * @param month
     * @return
     * @throws
     */
    public static Integer getDaysByYearMonth(int year, int month) {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        Integer maxDate = a.get(Calendar.DATE);
        return maxDate;
    }

    /**
     * 获取时间戳
     */
    public static String getTimeString(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        Calendar calendar = Calendar.getInstance();
        return df.format(calendar.getTime());
    }

    /**
     * 获取日期年份
     * 
     * @param date 日期
     * @return
     */
    public static int getYear(Date date) {
        if (date == null) {
            date = new Date();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 功能描述:返回月
     *
     * @param date Date 日期
     * @return 返回月份
     */
    public static int getMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) + 1;
    }

    /**
     * 功能描述:返回日
     *
     * @param date Date 日期
     * @return 返回日份
     */
    public static int getDayOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 功能描述:返回日
     *
     * @param date Date 日期
     * @return 返回日份
     */
    public static int getDayOfWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DAY_OF_WEEK) - 1;
    }

    /**
     * 功能描述:返回小
     *
     * @param date 日期
     * @return 返回小时
     */
    public static int getHour(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 功能描述:返回分
     *
     * @param date 日期
     * @return 返回分钟
     */
    public static int getMinute(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MINUTE);
    }

    /**
     * 返回秒钟
     *
     * @param date Date 日期
     * @return 返回秒钟
     */
    public static int getSecond(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.SECOND);
    }

    /**
     * 功能描述:返回毫
     *
     * @param date 日期
     * @return 返回毫
     */
    public static long getMillis(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getTimeInMillis();
    }

    /**
     * .获取今天的日期
     */
    public static String getTodayDate() {
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    }

    /**
     * 获取指定日期的每天开始时间
     * 
     * @param date
     * @return String
     */
    public static String getTodayStartTime(Date date) {
        return new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(date);
    }

    /**
     * 获取指定日期的每天结束时间
     * 
     * @param date
     * @return String
     */
    public static String getTodayEndTime(Date date) {
        return new SimpleDateFormat("yyyy-MM-dd 23:59:59").format(date);
    }

    /**
     * 得到几天前的时间
     * 
     * @param d
     * @param day
     * @return
     */
    public static String getDateBefore(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        if (day > 0) {
            now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        }
        return new SimpleDateFormat(DATE_SHORT_STR).format(now.getTime());
    }

    /**
     * 得到几天后的时间
     * 
     * @param d
     * @param day
     * @return
     */
    public static String getDateAfter(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
        return new SimpleDateFormat(DATE_SHORT_STR).format(now.getTime());
    }

    /**
     * 描述:计算两个日期所差的天数.
     * 
     * @param date1 第一个时间的毫秒表示
     * @param date2 第二个时间的毫秒表示
     * @return int 所差的天数
     */
    public static int getOffectDay(long date1, long date2) {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTimeInMillis(date1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTimeInMillis(date2);
        // 先判断是否同年
        int y1 = calendar1.get(Calendar.YEAR);
        int y2 = calendar2.get(Calendar.YEAR);
        int d1 = calendar1.get(Calendar.DAY_OF_YEAR);
        int d2 = calendar2.get(Calendar.DAY_OF_YEAR);
        int maxDays = 0;
        int day = 0;
        if (y1 - y2 > 0) {
            maxDays = calendar2.getActualMaximum(Calendar.DAY_OF_YEAR);
            day = d1 - d2 + maxDays;
        } else if (y1 - y2 < 0) {
            maxDays = calendar1.getActualMaximum(Calendar.DAY_OF_YEAR);
            day = d1 - d2 - maxDays;
        } else {
            day = d1 - d2;
        }
        return day;
    }

    /**
     * 描述:计算两个日期所差的小时数.
     * 
     * @param date1 第一个时间的毫秒表示
     * @param date2 第二个时间的毫秒表示
     * @return int 所差的小时数
     */
    public static int getOffectHour(long date1, long date2) {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTimeInMillis(date1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTimeInMillis(date2);
        int h1 = calendar1.get(Calendar.HOUR_OF_DAY);
        int h2 = calendar2.get(Calendar.HOUR_OF_DAY);
        int h = 0;
        int day = getOffectDay(date1, date2);
        h = h1 - h2 + day * 24;
        return h;
    }

    /**
     * 描述:计算两个日期所差的分钟数.
     * 
     * @param date1 第一个时间的毫秒表示
     * @param date2 第二个时间的毫秒表示
     * @return int 所差的分钟数
     */
    public static int getOffectMinutes(long date1, long date2) {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTimeInMillis(date1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTimeInMillis(date2);
        int m1 = calendar1.get(Calendar.MINUTE);
        int m2 = calendar2.get(Calendar.MINUTE);
        int h = getOffectHour(date1, date2);
        int m = 0;
        m = m1 - m2 + h * 60;
        return m;
    }

    /**
     * 描述:根据时间返回几天前或几分钟的描述.
     * 
     * @param strDate the str date
     * @return the string
     */
    public static String formatDateStr2Desc(String strDate, String outFormat) {

        DateFormat df = new SimpleDateFormat(DATE_LONG_STR);
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c2.setTime(df.parse(strDate));
            c1.setTime(new Date());
            int d = getOffectDay(c1.getTimeInMillis(), c2.getTimeInMillis());
            if (d == 0) {
                int h = getOffectHour(c1.getTimeInMillis(), c2.getTimeInMillis());
                if (h > 0) {
                    return h + "小时前";
                } else if (h < 0) {
                    return Math.abs(h) + "小时后";
                } else if (h == 0) {
                    int m = getOffectMinutes(c1.getTimeInMillis(), c2.getTimeInMillis());
                    if (m > 0) {
                        return m + "分钟前";
                    } else if (m < 0) {
                        return Math.abs(m) + "分钟后";
                    } else {
                        return "刚刚";
                    }
                }
            } else if (d > 0) {
                if (d == 1) {
                    return "昨天";
                } else if (d == 2) {
                    return "前天";
                }
            } else if (d < 0) {
                if (d == -1) {
                    return "明天";
                } else if (d == -2) {
                    return "后天";
                }
                return Math.abs(d) + "天后";
            }

            String out = getStringByFormat(strDate, outFormat);
            if (out != null && "".equals(out)) {
                return out;
            }
        } catch (Exception e) {
        }

        return strDate;
    }

    /**
     * 描述:获取milliseconds表示的日期时间的字符串.
     * 
     * @param format 格式化字符串,如:"yyyy-MM-dd HH:mm:ss"
     * @return String 日期时间字符串
     */
    public static String getStringByFormat(long milliseconds, String format) {
        String thisDateTime = null;
        try {
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            thisDateTime = mSimpleDateFormat.format(milliseconds);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return thisDateTime;
    }

    /**
     * 描述:获取指定日期时间的字符串,用于导出想要的格式.
     * 
     * @param strDate String形式的日期时间,必须为yyyy-MM-dd HH:mm:ss格式
     * @param format 输出格式化字符串,如:"yyyy-MM-dd HH:mm:ss"
     * @return String 转换后的String类型的日期时间
     */
    public static String getStringByFormat(String strDate, String format) {
        String mDateTime = null;
        try {
            Calendar c = new GregorianCalendar();
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(DATE_LONG_STR);
            c.setTime(mSimpleDateFormat.parse(strDate));
            SimpleDateFormat mSimpleDateFormat2 = new SimpleDateFormat(format);
            mDateTime = mSimpleDateFormat2.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mDateTime;
    }

    /**
     * 取指定日期为星期几
     * 
     * @param strDate 指定日期
     * @param inFormat 指定日期格式
     * @return String 星期几
     */
    public static String getWeekNumber(String strDate, String inFormat) {
        String week = "星期日";
        Calendar calendar = new GregorianCalendar();
        DateFormat df = new SimpleDateFormat(inFormat);
        try {
            calendar.setTime(df.parse(strDate));
        } catch (Exception e) {
            return "错误";
        }
        int intTemp = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        switch (intTemp) {
        case 0:
            week = "星期日";
            break;
        case 1:
            week = "星期一";
            break;
        case 2:
            week = "星期二";
            break;
        case 3:
            week = "星期三";
            break;
        case 4:
            week = "星期四";
            break;
        case 5:
            week = "星期五";
            break;
        case 6:
            week = "星期六";
            break;
        }
        return week;
    }

    /**
     * 判断当前日期是星期几<br>
     * <br>
     * 
     * @param pTime 修要判断的时间<br>
     * @return dayForWeek 判断结果<br>
     * @Exception 发生异常<br>
     */
    public static int dayForWeek(String pTime) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat(DATE_SHORT_STR);
        Calendar c = Calendar.getInstance();
        c.setTime(format.parse(pTime));
        int dayForWeek = 0;
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            dayForWeek = 7;
        } else {
            dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        }
        return dayForWeek;
    }

    /**
     * 获得当前周- 周一的日期
     * 
     * @Title: getCurrentMonday
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @return String
     * @throws
     */
    public static String getCurrentMonday() {
        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus);
        Date monday = currentDate.getTime();
        DateFormat df = DateFormat.getDateInstance();
        String preMonday = df.format(monday);
        return preMonday;
    }

    /**
     * 获得本周一与当前日期相差的天数
     * 
     * @Title: getMondayPlus
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @return int
     * @throws
     */
    public static int getMondayPlus() {
        Calendar cd = Calendar.getInstance();
        int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == 1) {
            return -6;
        } else {
            return 2 - dayOfWeek;
        }
    }

    /**
     * 获取当前周指定前后第几周的日期列表,week=0 表示获取当前周的日期列表
     * 
     * @Title: getCurrentOffsetWeekDatesList
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param week
     * @return List<String>
     * @throws
     */
    public static List<String> getCurrentOffsetWeekDatesList(int week) {
        List<String> dateList = new ArrayList<String>(7);
        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus);
        Date monday = currentDate.getTime();
        DateFormat df = DateFormat.getDateInstance();

        for (int i = 0; i < 7; i++) {
            dateList.add(df.format(addDay(monday, (week * 7 + i))));
        }
        return dateList;
    }

    /**
     * 获取指定年份的所有月份,返回格式[yyyy-MM]
    * @Title: getInitMonthMapWithZero 
    * @Description: TODO(这里用一句话描述这个方法的作用) 
    * @param year
    * @return
    * List<String> 
    * @throws
     */
    public static List<String> getInitMonthMapWithZero() {
        List<String> list = new ArrayList<String>();
        Calendar c = Calendar.getInstance();
        for (int i = 0; i < 12; i++) {
            int k = c.get(Calendar.YEAR);
            int j = c.get(Calendar.MONTH) + 1 - i;
            String date = "";
            if (j >= 1) {
                date = k + "-" + (j >= 10 ? "" : "0") + j;
            } else {
                int p = 11 - i;// 剩余循环次数
                int m = c.get(Calendar.YEAR) - 1;
                int n = c.get(Calendar.MONTH) + 2 + p;
                date = m + "-" + (n >= 10 ? "" : "0") + n;
            }
            list.add(date);
        }
        return list;
    }

    /**
     * 获取两个时间段的所有日期
     * @Title: getBetweenDate   
     * @Description: TODO(这里用一句话描述这个方法的作用)   
     * @param begin
     * @param end
     * @return      
     * List<String>      
     * @throws
     */
    public static List<String> getDayBetweenDate(String begin, String end) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<String> betweenList = new ArrayList<String>();
        try {
            Calendar startDay = Calendar.getInstance();
            startDay.setTime(format.parse(begin));
            startDay.add(Calendar.DATE, -1);

            while (true) {
                startDay.add(Calendar.DATE, 1);
                Date newDate = startDay.getTime();
                String newend = format.format(newDate);
                betweenList.add(newend);
                if (end.equals(newend)) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return betweenList;
    }

    public static List<String> getMonthBetweenDate(String minDate, String maxDate) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        ArrayList<String> result = new ArrayList<String>();
        try {
            Calendar min = Calendar.getInstance();
            Calendar max = Calendar.getInstance();
            min.setTime(format.parse(minDate));
            min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
            max.setTime(format.parse(maxDate));
            max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

            Calendar curr = min;
            while (curr.before(max)) {
                result.add(format.format(curr.getTime()));
                curr.add(Calendar.MONTH, 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
//        Calendar calendar=Calendar.getInstance();
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH");
//        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 1);
//        String newDate= df.format(calendar.getTime())+":59:59";
//        String nowDate=df.format(calendar.getTime())+":00:00";
//        Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);
    }
}

四、OrderOutMapper

/**
 * 
 */
package com.commons.mybatis;

import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 *
 */
public interface OrderOutMapper {

	public Integer insert(@Param("cloumnMapList") List<Map<String, String>> cloumnMap,
						  @Param("valueMapList") List<Map<String, Object>> valueMap);

    Integer insertDetails(@Param("cloumnMapList") List<Map<String, String>> cloumnMap,
						  @Param("valueMapList") List<Map<String, Object>> valueMap);
}

五、OrderOutMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<insert id="insert">
insert into stockout_order_query_trade
	<foreach collection="cloumnMapList" item="cloumnMap" index="index" separator =",">
		<foreach collection="cloumnMap.values" item="v" open="(" close=")" separator=",">
			${v}
		</foreach>
	</foreach>
	 values
	<foreach collection="valueMapList" item="valueMap" index="index" separator =",">
		<foreach collection="valueMap.values" item="v" open="(" close=")" separator=",">
	    	#{v}
		</foreach>
	</foreach>
</insert>

<insert id="insertDetails">
	insert into stockout_order_query_trade_details_list
	<foreach collection="cloumnMapList" item="cloumnMap" index="index" separator =",">
		<foreach collection="cloumnMap.values" item="v" open="(" close=")" separator=",">
			${v}
		</foreach>
	</foreach>
	values
	<foreach collection="valueMapList" item="valueMap" index="index" separator =",">
		<foreach collection="valueMap.values" item="v" open="(" close=")" separator=",">
			#{v}
		</foreach>
	</foreach>
</insert>

至此一个从第三方接口获取数据存入到本地数据库的方法就此完成,大家有不懂的可以在下方留言或者QQ咨询(1354031513)

  • 4
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值