package com.bqjrcar.blcmb.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>Title: CommonUtil</p>
* <p>Description: 日期格式常用处理类</p>
* <p>Copyright: </p>
* @author guotai
* @date 2016年5月15日 下午2:23:19
*
*/
public class DateUtil {
private final static Logger logger = LoggerFactory.getLogger(DateUtil.class);
/**
* yyyy-MM-dd HH:mm:ss
*/
public static final String YYYYMMDDHHMMSS = "yyyy-MM-dd HH:mm:ss";
/**
* yyyy-MM-dd HH:mm
*/
public static final String YYYYMMDDHHMM = "yyyy-MM-dd HH:mm";
/**
* yyyy-MM-dd
*/
public static final String YYYYMMDD = "yyyy-MM-dd";
/**
* yyyy-MM
*/
public static final String YYYYMM = "yyyy-MM";
/**
* HH:mm:ss
*/
public static final String HHMMSS = "HH:mm:ss";
public static final int second = 86400000;
/**
* EEEE
*/
public static final String WEEK = "EEEE";
public static final String[] weeks = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
public static final String[] weeksSimple = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
/**
* 字符串转化为Date
*
* @return String 日期字符串
* @throws ParseException
* @throws ParseException
*/
public static Date strToDate(String dateStr) {
try {
if (GeneralUtil.isEmpty(dateStr)) {
return null;
} else {
SimpleDateFormat sdf = new SimpleDateFormat();
return sdf.parse(dateStr);
}
} catch (ParseException e) {
logger.error("字符串转化为Date异常!dateStr:" + dateStr + e.getMessage());
throw new RuntimeException("字符串转化为Date异常!");
}
}
/**
* 字符串转化为Date
*
* @return String 日期字符串
* @throws ParseException
* @throws ParseException
*/
public static Date strToDate(String dateStr, String format) {
try {
if (GeneralUtil.isEmpty(dateStr)) {
return null;
} else {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.parse(dateStr);
}
} catch (ParseException e) {
logger.error("字符串转化为Date异常!dateStr:" + dateStr + e.getMessage());
throw new RuntimeException("字符串转化为Date异常!");
}
}
/**
* Date转化为字符串
*
* @param Date 日期
* @return String yyyy-MM-dd HH:mm:ss
*/
public static String dateToStr(Date date) {
if (date == null) {
return null;
} else {
SimpleDateFormat sdf = new SimpleDateFormat(YYYYMMDDHHMMSS);
return sdf.format(date);
}
}
/**
* Date转化为字符串
*
* @param Date 日期
* @param format 格式
* @return String
*/
public static String dateToStr(Date date, String format) {
if (date == null) {
return null;
} else {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
}
/**
* 格式A转换为格式B
* @param dateStr 日期
* @param oldformat 格式
* @param newFormat 格式
* @return String
*/
public static String convertFormat(String dateStr,String oldformat,String newFormat) {
Date date = DateUtil.strToDate(dateStr,oldformat);
return DateUtil.dateToStr(date, newFormat);
}
/**
* 获取当前日期且转换为long
*
* @param format 格式如:(yyyyMMdd、yyyyMMddHHmmss)
* @return String
*/
public static long dateToNum(Date date, String format) {
return Integer.parseInt(DateUtil.dateToStr(date, format));
}
/**
* 获取某一天
*
* @param days 天数
* @return Date
*/
public static Date add(int days) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, days);
return calendar.getTime();
}
/**
* 计算两日期之间天数
*
* @param startDate 起始日期
* @param endDate 结束日期
* @return int
*/
public static int getDay(Date startDate, Date endDate) {
if (startDate.after(endDate)) {
Date cal = startDate;
startDate = endDate;
endDate = cal;
}
long sl = startDate.getTime();
long el = endDate.getTime();
long ei = el - sl;
return (int) (ei / second);
}
/**
* 计算两日期之间天数
*
* @param startDate 起始日期
* @param endDate 結束日期
* @return int
* @throws ParseException
*/
public static int getDay(String startDate, String endDate) throws ParseException {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(YYYYMMDD);
Date s = sdf.parse(startDate);
calendar.setTime(s);
long timethis = calendar.getTimeInMillis();
Date e = sdf.parse(endDate);
calendar.setTime(e);
long timeend = calendar.getTimeInMillis();
return (int) (timeend - timethis) / second;
}
/**
* 得到今天的日期时间数组串,前面小时间,后面大时间
*
* @return ['2014-03-29 00:00:00','2014-03-29 23:59:59']
*/
public static String[] getNearTodayDateTimeStr() {
Calendar cal = Calendar.getInstance();
String today = dateToStr(cal.getTime(), YYYYMMDD);
return new String[] { today + " 00:00:00", today + " 23:59:59" };
}
/**
* Date转化为字符串
*
* @param Date 日期
* @param b (true 加 23:59:59,false加 00:00:00)
* @return String
*/
public static String appendStr(Date date, boolean b) {
if (b) {
return DateUtil.dateToStr(date, DateUtil.YYYYMMDD) + " 23:59:59";
} else {
return DateUtil.dateToStr(date, DateUtil.YYYYMMDD) + " 00:00:00";
}
}
/**
* Date转化为字符串
*
* @param Date 日期
* @param b (true 加 23:59:59,false加 00:00:00)
* @return String
*/
public static String appendStr(String dateStr, boolean b) {
if (b) {
return dateStr + " 23:59:59";
} else {
return dateStr + " 00:00:00";
}
}
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package com.bqjrcar.web.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONStringer;
import net.sf.json.util.JSONTokener;
import net.sf.json.util.JSONUtils;
/**
* @Title: JsonUtil.java
* @Package com.billionsfinance.bqap.util
* @Description:JSON处理工具类
* @author guotai
* @date 2015年11月05日 上午12:00:19
* @version V1.0
*/
public class JsonUtil {
private final static String regex = "\"([^\\\" ]+?)\":";
/**
* 一个方法解析多层json数据 json + 正则 + 递归
* @see {@link java.util.regex.Matcher}, {@link java.util.regex.Pattern}
* @param jsonStr
* @return {@link java.util.Map} or {@link java.util.List} or {@link java.lang.String}
*/
public static Object jsonParse(final String jsonStr) {
if (jsonStr == null) throw new NullPointerException("JsonString shouldn't be null");
try {
if (isJsonObject(jsonStr)) {
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(jsonStr);
final Map<String, Object> map = new HashMap<String, Object>();
final JSONObject jsonObject = JSONObject.fromObject(jsonStr);
try {
for (; matcher.find(); ) {
String groupName = matcher.group(1);
Object obj = jsonObject.opt(groupName);
if (isJsonObject(obj+"") || isJsonArray(obj+"")) {
matcher.region(matcher.end() + (obj+"").replace("\\", "").length(), matcher.regionEnd());
map.put(groupName, jsonParse(obj+""));
} else {
map.put(groupName, obj+"");
}
}
} catch (Exception e) {
}
return map;
} else if (isJsonArray(jsonStr)) {
List<Object> list = new ArrayList<Object>();
try {
JSONArray jsonArray = JSONArray.fromObject(jsonStr);
for (int i = 0; i < jsonArray.size(); i++) {
Object object = jsonArray.opt(i);
list.add(jsonParse(object+""));
}
} catch (Exception e) {
}
return list;
}
} catch (Exception e) {
}
return jsonStr;
}
/**
* To determine whether a string is JsonObject {@link org.json.JSONObject}
* @param jsonStr {@link java.lang.String}
* @return boolean
*/
private static boolean isJsonObject(final String jsonStr) {
if (jsonStr == null) return false;
return Pattern.matches("^\\{.*\\}$", jsonStr.trim());
}
/**
* To determine whether a string is JsonArray {@link org.json.JSONArray};
* @param jsonStr {@link java.lang.String}
* @return boolean
*/
private static boolean isJsonArray(final String jsonStr) {
if (jsonStr == null) return false;
return Pattern.matches("^\\[.*\\]$", jsonStr.trim());
}
/**
* 将对象分装为json字符串 (json + 递归)
* @param obj 参数应为{@link java.util.Map} 或者 {@link java.util.List}
* @return
*/
@SuppressWarnings("unchecked")
public static Object jsonEnclose(Object obj) {
try {
if (obj instanceof Map) { //如果是Map则转换为JsonObject
Map<String, Object> map = (Map<String, Object>)obj;
Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
JSONStringer jsonStringer = (JSONStringer) new JSONStringer().object();
while (iterator.hasNext()) {
Entry<String, Object> entry = iterator.next();
jsonStringer.key(entry.getKey()).value(jsonEnclose(entry.getValue()));
}
String jonstr = jsonStringer.endObject().toString();
JSONTokener jsonTokener = new JSONTokener(jonstr);
JSONObject jsonObject =JSONObject.fromObject(jsonTokener);
return jsonObject;
} else if (obj instanceof List) { //如果是List则转换为JsonArray
List<Object> list = (List<Object>)obj;
JSONStringer jsonStringer = (JSONStringer) new JSONStringer().array();
for (int i = 0; i < list.size(); i++) {
jsonStringer.value(jsonEnclose(list.get(i)));
}
String jonstr = jsonStringer.endArray().toString();
JSONArray jsonArray =JSONArray.fromObject(new JSONTokener(jonstr));
return jsonArray;
} else {
return obj;
}
} catch (Exception e) {
return e.getMessage();
}
}
/**
* 从一个JSON 对象字符格式中得到一个java对象,形如:
* {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...}}
* @param object
* @param clazz
* @return
*/
public static Object getDTO(String jsonString, Class clazz){
JSONObject jsonObject = null;
try{
setDataFormat2JAVA();
jsonObject = JSONObject.fromObject(jsonString);
}catch(Exception e){
e.printStackTrace();
}
return JSONObject.toBean(jsonObject, clazz);
}
/**
* 从一个JSON 对象字符格式中得到一个java对象,其中beansList是一类的集合,形如:
* {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...},
* beansList:[{}, {}, ...]}
* @param jsonString
* @param clazz
* @param map 集合属性的类型 (key : 集合属性名, value : 集合属性类型class) eg: ("beansList" : Bean.class)
* @return
*/
public static Object getDTO(String jsonString, Class clazz, Map map){
JSONObject jsonObject = null;
try{
//setDataFormat2JAVA();
jsonObject = JSONObject.fromObject(jsonString);
}catch(Exception e){
e.printStackTrace();
}
return JSONObject.toBean(jsonObject, clazz, map);
}
/**
* 从一个JSON数组得到一个java对象数组,形如:
* [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...]
* @param object
* @param clazz
* @return
*/
public static Object[] getDTOArray(String jsonString, Class clazz){
setDataFormat2JAVA();
JSONArray array = JSONArray.fromObject(jsonString);
Object[] obj = new Object[array.size()];
for(int i = 0; i < array.size(); i++){
JSONObject jsonObject = array.getJSONObject(i);
obj[i] = JSONObject.toBean(jsonObject, clazz);
}
return obj;
}
/**
* 从一个JSON数组得到一个java对象数组,形如:
* [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...]
* @param object
* @param clazz
* @param map
* @return
*/
public static Object[] getDTOArray(String jsonString, Class clazz, Map map){
setDataFormat2JAVA();
JSONArray array = JSONArray.fromObject(jsonString);
Object[] obj = new Object[array.size()];
for(int i = 0; i < array.size(); i++){
JSONObject jsonObject = array.getJSONObject(i);
obj[i] = JSONObject.toBean(jsonObject, clazz, map);
}
return obj;
}
/**
* 从一个JSON数组得到一个java对象集合
* @param object
* @param clazz
* @return
*/
public static List getDTOList(String jsonString, Class clazz){
setDataFormat2JAVA();
JSONArray array = JSONArray.fromObject(jsonString);
List list = new ArrayList();
for(Iterator iter = array.iterator(); iter.hasNext();){
JSONObject jsonObject = (JSONObject)iter.next();
list.add(JSONObject.toBean(jsonObject, clazz));
}
return list;
}
/**
* 从一个JSON数组得到一个java对象集合,其中对象中包含有集合属性
* @param object
* @param clazz
* @param map 集合属性的类型
* @return
*/
public static List getDTOList(String jsonString, Class clazz, Map map){
setDataFormat2JAVA();
JSONArray array = JSONArray.fromObject(jsonString);
List list = new ArrayList();
for(Iterator iter = array.iterator(); iter.hasNext();){
JSONObject jsonObject = (JSONObject)iter.next();
list.add(JSONObject.toBean(jsonObject, clazz, map));
}
return list;
}
/**
* 从json HASH表达式中获取一个map,该map支持嵌套功能
* 形如:{"id" : "johncon", "name" : "小强"}
* 注意commons-collections版本,必须包含org.apache.commons.collections.map.MultiKeyMap
* @param object
* @return
*/
public static Map getMapFromJson(String jsonString) {
JSONObject jsonObject = JSONObject.fromObject(jsonString);
Map map = new HashMap();
for(Iterator iter = jsonObject.keys(); iter.hasNext();){
String key = (String)iter.next();
map.put(key, jsonObject.get(key));
}
return map;
}
/**
* 从json数组中得到相应java数组
* json形如:["123", "456"]
* @param jsonString
* @return
*/
public static Object[] getObjectArrayFromJson(String jsonString) {
JSONArray jsonArray = JSONArray.fromObject(jsonString);
return jsonArray.toArray();
}
private static void setDataFormat2JAVA(){
//设定日期转换格式
JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"}));
}
public static String beanToJson(Object obj){
String json = "{}";
if (obj instanceof List){
List<Object> list = (List<Object>)obj;
if(list != null && list.size() > 0){
JSONArray arry = JSONArray.fromObject(list);
json = arry.toString();
}
}else{
if(obj != null ){
JSONObject jsonObj = JSONObject.fromObject(obj);
json = jsonObj.toString();
}
}
return json;
}
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package com.bqjrcar.web.util;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class OutUtil {
private HttpServletRequest request;
private HttpServletResponse response;
private HttpSession session;
public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){
this.request = request;
this.response = response;
this.session = request.getSession();
}
public void returnJson(Map<String, Object> map){
PrintWriter out = null;
try {
response.setContentType("application/json ;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
out = response.getWriter();
// String jsonstr = JsonUtil.jsonEnclose(map).toString();
// out.print(jsonstr);
} catch (IOException e) {
}finally{
if(out != null){
out.flush();
out.close();
}
}
}
public void returnStr(String str){
PrintWriter out = null;
try {
out = response.getWriter();
out.print(str);
} catch (IOException e) {
}finally{
if(out != null){
out.flush();
out.close();
}
}
}
public void returnJson(String json){
PrintWriter out = null;
try {
response.setContentType("application/json ;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
out = response.getWriter();
out.print(json);
}catch (IOException e){
}finally{
if(out != null){
out.flush();
out.close();
}
}
}
public void returnJson(String code,String msg){
PrintWriter out = null;
try {
response.setContentType("application/json ;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
out = response.getWriter();
Map map = new HashMap();
map.put("code", code);
map.put("msg", msg);
// String jsonstr = JsonUtil.jsonEnclose(map).toString();
// out.print(jsonstr);
} catch (IOException e) {
}finally{
if(out != null){
out.flush();
out.close();
}
}
}
}