Commit 9dc0393b by java-李谡

使用阿里代码规范插件扫描后修改

parent 0a101d99
...@@ -3,16 +3,6 @@ ...@@ -3,16 +3,6 @@
*/ */
package com.foc.hrm.service; package com.foc.hrm.service;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.lang3.StringUtils;
import com.foc.conf.Constants; import com.foc.conf.Constants;
import com.foc.hrm.entity.UserEntity; import com.foc.hrm.entity.UserEntity;
import com.foc.phone.area.PhoneAreaEntity; import com.foc.phone.area.PhoneAreaEntity;
...@@ -21,18 +11,27 @@ import com.foc.seat.entity.SeatEntity; ...@@ -21,18 +11,27 @@ import com.foc.seat.entity.SeatEntity;
import com.foc.util.DBHandler; import com.foc.util.DBHandler;
import com.foc.util.DBHelper; import com.foc.util.DBHelper;
import com.foc.util.Util; import com.foc.util.Util;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.lang3.StringUtils;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/** /**
*
* @team IT Team
* @author renmb * @author renmb
* @version 1.0 * @version 1.0
* @team IT Team
* @time 2016年10月30日 * @time 2016年10月30日
*/ */
public class HRMUpdatePreMobileService { public class HRMUpdatePreMobileService {
QueryRunner run = null; QueryRunner run = null;
public HRMUpdatePreMobileService(){
public HRMUpdatePreMobileService() {
try { try {
this.run = new QueryRunner(DBHelper.getDataSource()); this.run = new QueryRunner(DBHelper.getDataSource());
...@@ -41,23 +40,26 @@ public class HRMUpdatePreMobileService { ...@@ -41,23 +40,26 @@ public class HRMUpdatePreMobileService {
e.printStackTrace(); e.printStackTrace();
} }
} }
public void start(boolean isUpdateMobile) { public void start(boolean isUpdateMobile) {
ResultSetHandler<List<UserEntity>> handler = new BeanListHandler<UserEntity>(UserEntity.class); ResultSetHandler<List<UserEntity>> handler = new BeanListHandler<UserEntity>(UserEntity.class);
String query = "SELECT *,phone_number AS phoneNumber,mobile_nubmer AS mobileNubmer,premobile_confirmed AS premobileConfirmed FROM " + Constants.SYS_USER ; String query = "SELECT *,phone_number AS phoneNumber,mobile_nubmer AS mobileNubmer,premobile_confirmed AS premobileConfirmed FROM " + Constants.SYS_USER;
//+ " WHERE id='1000866011'";//premobile_confirmed='UNCONFIRMED'";// +" WHERE mobile LIKE '%+%'"; //+ " WHERE id='1000866011'";//premobile_confirmed='UNCONFIRMED'";// +" WHERE mobile LIKE '%+%'";
List<UserEntity> list = null; List<UserEntity> list = null;
try { try {
list = run.query(query, handler); list = run.query(query, handler);
if (list != null && list.size() != 0){ if (list != null && list.size() != 0) {
for(UserEntity user:list){ for (UserEntity user : list) {
if(isUpdateMobile && (StringUtils.isBlank(user.getMobileNubmer()) || // 此手机号未处理过
!user.getMobileNubmer().contains(user.getMobile()))){// 此手机号未处理过 if (isUpdateMobile && (StringUtils.isBlank(user.getMobileNubmer()) ||
!user.getMobileNubmer().contains(user.getMobile()))) {
updatePreMobile(user.getMobile(), user.getId());// 格式化手机号码 // 格式化手机号码
updatePreMobile(user.getMobile(), user.getId());
} }
updateWorkPhone(user.getPhone(), user.getPhoneNumber(), user.getId());// 格式化座机号码 // 格式化座机号码
updateWorkPhone(user.getPhone(), user.getPhoneNumber(), user.getId());
} }
} }
} catch (Exception e) { } catch (Exception e) {
...@@ -66,14 +68,14 @@ public class HRMUpdatePreMobileService { ...@@ -66,14 +68,14 @@ public class HRMUpdatePreMobileService {
} }
// 席位电话处理 // 席位电话处理
ResultSetHandler<List<SeatEntity>> seatHandler = new BeanListHandler<SeatEntity>(SeatEntity.class); ResultSetHandler<List<SeatEntity>> seatHandler = new BeanListHandler<SeatEntity>(SeatEntity.class);
String sql = "SELECT `id`, `seat_name` AS seatName,`seat_phone` AS seatPhone,`seat_phone_number` AS seatPhoneNumber FROM " + Constants.FOC_SEATS ; String sql = "SELECT `id`, `seat_name` AS seatName,`seat_phone` AS seatPhone,`seat_phone_number` AS seatPhoneNumber FROM " + Constants.FOC_SEATS;
//+ " WHERE id='1000866011'";//premobile_confirmed='UNCONFIRMED'";// +" WHERE mobile LIKE '%+%'"; //+ " WHERE id='1000866011'";//premobile_confirmed='UNCONFIRMED'";// +" WHERE mobile LIKE '%+%'";
List<SeatEntity> seatList = null; List<SeatEntity> seatList = null;
try { try {
seatList = run.query(sql, seatHandler); seatList = run.query(sql, seatHandler);
if (seatList != null && seatList.size() != 0){ if (seatList != null && seatList.size() != 0) {
for(SeatEntity seat:seatList){ for (SeatEntity seat : seatList) {
updateSeatPhone(seat.getSeatPhone(), seat.getSeatPhoneNumber(), seat.getId());// 格式化座机号码 updateSeatPhone(seat.getSeatPhone(), seat.getSeatPhoneNumber(), seat.getId());// 格式化座机号码
} }
...@@ -83,21 +85,21 @@ public class HRMUpdatePreMobileService { ...@@ -83,21 +85,21 @@ public class HRMUpdatePreMobileService {
e.printStackTrace(); e.printStackTrace();
} }
} }
public String getWorkPhone(String workPhone) { public String getWorkPhone(String workPhone) {
if(StringUtils.isNotBlank(workPhone)){ if (StringUtils.isNotBlank(workPhone)) {
workPhone = workPhone.replaceAll("[^\\d|+]+", ""); workPhone = workPhone.replaceAll("[^\\d^,^#|+]+", "");
// if(workPhone.length() < 7 || workPhone.matches("0+")) if (workPhone.matches("0+")) {
if(workPhone.matches("0+")){
workPhone = ""; workPhone = "";
} else if(workPhone.startsWith("0") == false){// 非0开头的号码需要处理 // 非0开头的号码需要处理
if(workPhone.startsWith("1") && workPhone.length() == 11){ } else if (workPhone.startsWith("0") == false) {
if (workPhone.startsWith("1") && workPhone.length() == 11) {
workPhone = ""; workPhone = "";
} }
} }
if(workPhone.startsWith("+") == false){// 外国号码前面加拨3个000 // 外国号码前面加拨3个000
if (workPhone.startsWith("+") == false) {
workPhone = workPhone.replace("+", ""); workPhone = workPhone.replace("+", "");
} }
} else { } else {
...@@ -106,10 +108,11 @@ public class HRMUpdatePreMobileService { ...@@ -106,10 +108,11 @@ public class HRMUpdatePreMobileService {
} }
return workPhone; return workPhone;
} }
private boolean updateSeatPhone(String phone, String lastShowPhone, String seatId) { private boolean updateSeatPhone(String phone, String lastShowPhone, String seatId) {
try { try {
String showPhone = Util.formatedWorkPhone(phone); String showPhone = Util.formatedWorkPhone(phone);
if(showPhone.equals(lastShowPhone) == false){// 号码有变化 if (showPhone.equals(lastShowPhone) == false) {// 号码有变化
DBHandler dBHandler = new DBHandler(); DBHandler dBHandler = new DBHandler();
Map<String, Object> columnMap = new TreeMap<String, Object>(); Map<String, Object> columnMap = new TreeMap<String, Object>();
...@@ -125,14 +128,12 @@ public class HRMUpdatePreMobileService { ...@@ -125,14 +128,12 @@ public class HRMUpdatePreMobileService {
} }
return false; return false;
} }
private boolean updateWorkPhone(String phone, String lastShowPhone, String userId) { private boolean updateWorkPhone(String phone, String lastShowPhone, String userId) {
try { try {
// if(StringUtils.isBlank(phone))
// phone = "";
String workPhone = getWorkPhone(phone); String workPhone = getWorkPhone(phone);
// if(StringUtils.isBlank(phone)) // 号码有变化
// return false; if (!workPhone.equals(phone)) {
if(workPhone.equals(phone) == false){// 号码有变化
DBHandler dBHandler = new DBHandler(); DBHandler dBHandler = new DBHandler();
Map<String, Object> columnMap = new TreeMap<String, Object>(); Map<String, Object> columnMap = new TreeMap<String, Object>();
...@@ -144,7 +145,8 @@ public class HRMUpdatePreMobileService { ...@@ -144,7 +145,8 @@ public class HRMUpdatePreMobileService {
} }
String phoneNumber = Util.formatedWorkPhone(workPhone); String phoneNumber = Util.formatedWorkPhone(workPhone);
if(phoneNumber.equals(lastShowPhone) == false){// 号码有变化 // 号码有变化
if (phoneNumber.equals(lastShowPhone) == false) {
DBHandler dBHandler = new DBHandler(); DBHandler dBHandler = new DBHandler();
Map<String, Object> columnMap = new TreeMap<String, Object>(); Map<String, Object> columnMap = new TreeMap<String, Object>();
...@@ -160,84 +162,95 @@ public class HRMUpdatePreMobileService { ...@@ -160,84 +162,95 @@ public class HRMUpdatePreMobileService {
} }
return false; return false;
} }
/** /**
* 修改手机号前加拨0 * 修改手机号前加拨0
* 1、 北京手机号前加拨1个0 * 1、 北京手机号前加拨1个0
* 2、 国内非北京手机号加拨2个0 * 2、 国内非北京手机号加拨2个0
* 3、 国外手机号前面加拨3个0 * 3、 国外手机号前面加拨3个0
* *
* @author renmb
* @time 2016年10月30日
* @param mobile * @param mobile
* @param userId * @param userId
* @author renmb
* @time 2016年10月30日
*/ */
private boolean updatePreMobile(String mobile, String userId) { private boolean updatePreMobile(String mobile, String userId) {
try { try {
if(StringUtils.isBlank(mobile)) if (StringUtils.isBlank(mobile)) {
return false; return false;
}
DBHandler dBHandler = new DBHandler(); DBHandler dBHandler = new DBHandler();
Map<String, Object> columnMap = new TreeMap<String, Object>(); Map<String, Object> columnMap = new TreeMap<String, Object>();
Map<String, Object> whereMap = new TreeMap<String, Object>(); Map<String, Object> whereMap = new TreeMap<String, Object>();
String[] species = mobile.split("\\s+");// 只使用第一个手机号 // String[] species = mobile.split("\\s+");// 只使用第一个手机号
if(species.length>1 && species[0].matches("1\\d+") && species[1].matches("1\\d+")){ // if(species.length>1 && species[0].matches("1\\d+") && species[1].matches("1\\d+")){
//
mobile = species[0]; // mobile = species[0];
} // }
mobile = mobile.replaceAll("+", "+");// 处理错误字符 // 处理错误字符
mobile = mobile.replaceAll("[^0-9|+]+", "");// 将非电话号码替换为空 mobile = mobile.replaceAll("+", "+");
System.out.println("mobile:"+mobile); // 将除数字和,#字符外的内容替换为空
if(StringUtils.isBlank(mobile)){// 手机号不存在 mobile = mobile.replaceAll("[^0-9^,^#|+]+", "");
// 手机号不存在
if (StringUtils.isBlank(mobile)) {
return false; return false;
} else if(mobile.startsWith("+")){// 国外手机号,前面加拨3个0 // 国外手机号,前面加拨3个0
} else if (mobile.startsWith("+")) {
columnMap.put("premobile", "000"); columnMap.put("premobile", "000");
columnMap.put("mobile_nubmer", "000"+mobile.replace("+", "")); columnMap.put("mobile_nubmer", "000" + mobile.replace("+", ""));
whereMap.put("id", userId); whereMap.put("id", userId);
System.out.println(mobile + ":国外号码更改后,mobile_number=" + columnMap.get("mobile_nubmer"));
dBHandler.update(Constants.SYS_USER, columnMap, whereMap); dBHandler.update(Constants.SYS_USER, columnMap, whereMap);
return true; return true;
} else if(mobile.matches("\\d+")){ } else if (mobile.matches("\\d+")) {
PhoneAreaEntity area = PhoneAreaUtil.get360PhoneArea(mobile); PhoneAreaEntity area = PhoneAreaUtil.get360PhoneArea(mobile);
if(area != null && StringUtils.isNotBlank(area.getProvince())){// 能够查到省份信息 // 能够查到省份信息
if (area != null && StringUtils.isNotBlank(area.getProvince())) {
if(area.getProvince().contains("北京") if (area.getProvince().contains("北京")
|| (StringUtils.isNotBlank(area.getCity()) && area.getCity().contains("北京"))){// 北京前面加拨一个0 // 北京前面加拨一个0
|| (StringUtils.isNotBlank(area.getCity()) && area.getCity().contains("北京"))) {
columnMap.put("mobile_nubmer", "0"+mobile);// 加拨1个0 // 加拨1个0
columnMap.put("mobile_nubmer", "0" + mobile);
columnMap.put("premobile", "0"); columnMap.put("premobile", "0");
columnMap.put("mobile_province", "北京"); columnMap.put("mobile_province", "北京");
columnMap.put("mobile_city", "北京"); columnMap.put("mobile_city", "北京");
columnMap.put("mobile_sp", StringUtils.isBlank(area.getSp()) ? "" : area.getSp()); columnMap.put("mobile_sp", StringUtils.isBlank(area.getSp()) ? "" : area.getSp());
} else {// 非北京号码加拨两个0 } else {
// 非北京号码加拨两个0
columnMap.put("mobile_nubmer", "00"+mobile);// 加拨2个0 columnMap.put("mobile_nubmer", "00" + mobile);
columnMap.put("premobile", "00"); columnMap.put("premobile", "00");
columnMap.put("mobile_province", area.getProvince()); columnMap.put("mobile_province", area.getProvince());
columnMap.put("mobile_city", StringUtils.isBlank(area.getCity()) ? "" : area.getCity()); columnMap.put("mobile_city", StringUtils.isBlank(area.getCity()) ? "" : area.getCity());
columnMap.put("mobile_sp", StringUtils.isBlank(area.getSp()) ? "" : area.getSp()); columnMap.put("mobile_sp", StringUtils.isBlank(area.getSp()) ? "" : area.getSp());
} }
whereMap.put("id", userId); whereMap.put("id", userId);
System.out.println(mobile + ":查到归属地,mobile_number=" + columnMap.get("mobile_nubmer"));
dBHandler.update(Constants.SYS_USER, columnMap, whereMap); dBHandler.update(Constants.SYS_USER, columnMap, whereMap);
return true; return true;
} }
} }
//否则mobile=mobile_number
columnMap.put("mobile_nubmer", mobile);
columnMap.put("premobile", "");
columnMap.put("mobile_province", "");
columnMap.put("mobile_city", "");
columnMap.put("mobile_sp", "");
whereMap.put("id", userId);
System.out.println(mobile + ":手机号码不改变,mobile=mobile_number");
dBHandler.update(Constants.SYS_USER, columnMap, whereMap);
return true;
} catch (Exception e) { } catch (Exception e) {
// TODO: handle exception // TODO: handle exception
} }
return false; return false;
} }
// public static void main(String[] args){
// String getMobileNubmer = null;//"01A212"; public static void main(String[] args) {
// String getMobile = "1212"; HRMUpdatePreMobileService service = new HRMUpdatePreMobileService();
// boolean isUpdateMobile = true; // System.out.println(service.updatePreMobile("00013803779497", "1"));
// if(isUpdateMobile && (StringUtils.isBlank(getMobileNubmer) || System.out.println(service.updateWorkPhone("00016462485041,9694264088,053601046310#", "", "1"));
// !getMobileNubmer.contains(getMobile))){// 此手机号未处理过 // System.out.println(service.getWorkPhone("00016462485041,9694264088,053601046310#"));
// System.out.println("updatePreMobile(user.getMobile(), user.getId())"); // System.out.println(service.updatePreMobile("00016462485041,9694264088,053601046310#","1"));
// } }
// System.out.println("END");
// }
} }
...@@ -33,13 +33,14 @@ import com.alibaba.druid.pool.DruidDataSource; ...@@ -33,13 +33,14 @@ import com.alibaba.druid.pool.DruidDataSource;
public class DBHelper { public class DBHelper {
private final static Map<String, DruidDataSource> POOL = new HashMap<String, DruidDataSource>(6);; private final static Map<String, DruidDataSource> POOL = new HashMap<String, DruidDataSource>(6);
;
private static String defaultName = null; private static String defaultName = null;
private final static Object object = new Object(); private final static Object object = new Object();
private final static DBHelper factory = new DBHelper(); private final static DBHelper factory = new DBHelper();
public DBHelper(){ public DBHelper() {
init(); init();
} }
...@@ -47,13 +48,15 @@ public class DBHelper { ...@@ -47,13 +48,15 @@ public class DBHelper {
return factory; return factory;
} }
/** /**
* 初始化数据库 * 初始化数据库
*
* @throws FileNotFoundException * @throws FileNotFoundException
* @throws DocumentException * @throws DocumentException
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static void init(){ private static void init() {
InputStream in = null; InputStream in = null;
SAXReader reader = null; SAXReader reader = null;
...@@ -194,12 +197,12 @@ public class DBHelper { ...@@ -194,12 +197,12 @@ public class DBHelper {
dataSource.setConnectionProperties(entry.getTextTrim()); dataSource.setConnectionProperties(entry.getTextTrim());
} else if ((key.equals("name")) || (key.equals("group"))) { } else if ((key.equals("name")) || (key.equals("group"))) {
name = entry.getTextTrim(); name = entry.getTextTrim();
if(defaultName == null){ if (defaultName == null) {
defaultName = name; defaultName = name;
} }
} }
} }
System.out.println(name+" => " + url); System.out.println(name + " => " + url);
POOL.put(name, dataSource); POOL.put(name, dataSource);
} }
} catch (DocumentException e) { } catch (DocumentException e) {
...@@ -208,40 +211,46 @@ public class DBHelper { ...@@ -208,40 +211,46 @@ public class DBHelper {
// TODO: handle exception // TODO: handle exception
} catch (Exception e) { } catch (Exception e) {
// TODO: handle exception // TODO: handle exception
} finally{ } finally {
if(in != null){ if (in != null) {
try { try {
in.close(); in.close();
} catch (IOException e) {} } catch (IOException e) {
} }
} }
} }
}
public static DataSource getDataSource() throws SQLException { public static DataSource getDataSource() throws SQLException {
return getDataSource(defaultName); return getDataSource(defaultName);
} }
public static DataSource getDataSource(String name) throws SQLException { public static DataSource getDataSource(String name) throws SQLException {
synchronized(object){ synchronized (object) {
return POOL.get(name); return POOL.get(name);
} }
} }
/** /**
* 获取连接 * 获取连接
* @time 2015-07-01 *
* @author renmb
* @param name * @param name
* @return * @return
* @throws SQLException * @throws SQLException
* @time 2015-07-01
* @author renmb
*/ */
public static Connection getConnection(String name) throws SQLException { public static Connection getConnection(String name) throws SQLException {
synchronized(object){ synchronized (object) {
DataSource dataSource = POOL.get(name); DataSource dataSource = POOL.get(name);
Connection connection = dataSource.getConnection(); Connection connection = dataSource.getConnection();
if(connection == null){ if (connection == null) {
throw new SQLException("Unexpected: cannot get connection from pool"); throw new SQLException("Unexpected: cannot get connection from pool");
} }
return connection; return connection;
} }
} }
public static Connection getConnection() throws SQLException { public static Connection getConnection() throws SQLException {
return getConnection(defaultName); return getConnection(defaultName);
...@@ -249,43 +258,55 @@ public class DBHelper { ...@@ -249,43 +258,55 @@ public class DBHelper {
/** /**
* 关闭链接 * 关闭链接
*
* @param conn
* @time 2015-07-01 * @time 2015-07-01
* @author renmb * @author renmb
* @param conn
*/ */
public static void close(Connection conn){ public static void close(Connection conn) {
if(conn == null) if (conn == null) {
return ; return;
}
try { try {
conn.close(); conn.close();
} catch (Exception e) {} } catch (Exception e) {
}
} }
/** /**
* 关闭Statement * 关闭Statement
*
* @param stmt
* @time 2015-07-01 * @time 2015-07-01
* @author renmb * @author renmb
* @param stmt
*/ */
public static void close(Statement stmt){ public static void close(Statement stmt) {
if(stmt == null) if (stmt == null) {
return ; return;
}
try { try {
stmt.close(); stmt.close();
} catch (Exception e) {} } catch (Exception e) {
}
} }
/** /**
* 关闭ResultSet * 关闭ResultSet
*
* @param rs
* @time 2015-07-01 * @time 2015-07-01
* @author renmb * @author renmb
* @param rs
*/ */
public static void close(ResultSet rs){ public static void close(ResultSet rs) {
if(rs == null) if (rs == null) {
return ; return;
}
try { try {
rs.close(); rs.close();
} catch (Exception e) {} } catch (Exception e) {
}
} }
public static void close(Connection conn, Statement stmt, ResultSet rs) { public static void close(Connection conn, Statement stmt, ResultSet rs) {
close(rs); close(rs);
close(stmt); close(stmt);
...@@ -293,24 +314,29 @@ public class DBHelper { ...@@ -293,24 +314,29 @@ public class DBHelper {
} }
public static String getString(Object data, String want) { public static String getString(Object data, String want) {
if(data == null) if (data == null) {
return want; return want;
}
try { try {
String val = String.valueOf(data); String val = String.valueOf(data);
if(val == null || val.trim().isEmpty()) if (val == null || val.trim().isEmpty()) {
return want; return want;
}
return val.trim(); return val.trim();
} catch (Exception e) {} } catch (Exception e) {
}
return want; return want;
} }
/** /**
* 预编译SQL * 预编译SQL
* @time 2015-07-01 *
* @author renmb
* @param table * @param table
* @param colums * @param colums
* @return * @return
* @throws SQLException * @throws SQLException
* @time 2015-07-01
* @author renmb
*/ */
public static String buildInsertPreparedSQL(String table, String... colums) public static String buildInsertPreparedSQL(String table, String... colums)
throws SQLException { throws SQLException {
...@@ -333,21 +359,24 @@ public class DBHelper { ...@@ -333,21 +359,24 @@ public class DBHelper {
marks.delete(0, marks.length()); marks.delete(0, marks.length());
return fields.toString(); return fields.toString();
} }
/** /**
* 插入一行数据 * 插入一行数据
* @time 2015-07-01 *
* @author renmb
* @param name * @param name
* @param table * @param table
* @param row * @param row
* @param isGeneratedKey * @param isGeneratedKey
* @return * @return
* @throws SQLException * @throws SQLException
* @time 2015-07-01
* @author renmb
*/ */
public static int insert(String name, String table, Map<String, Object> row, boolean isGeneratedKey){ public static int insert(String name, String table, Map<String, Object> row, boolean isGeneratedKey) {
if(name == null || table == null || row == null) if (name == null || table == null || row == null) {
return -1; return -1;
synchronized(object){ }
synchronized (object) {
String query = null; String query = null;
PreparedStatement ps = null; PreparedStatement ps = null;
Connection conn = null; Connection conn = null;
...@@ -356,9 +385,9 @@ public class DBHelper { ...@@ -356,9 +385,9 @@ public class DBHelper {
conn = getConnection(name); conn = getConnection(name);
query = buildInsertPreparedSQL(table, (String[]) row.keySet() query = buildInsertPreparedSQL(table, (String[]) row.keySet()
.toArray(new String[row.keySet().size()])); .toArray(new String[row.keySet().size()]));
if(isGeneratedKey){ if (isGeneratedKey) {
ps = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); ps = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
} else{ } else {
ps = conn.prepareStatement(query); ps = conn.prepareStatement(query);
} }
int index = 1; int index = 1;
...@@ -366,7 +395,7 @@ public class DBHelper { ...@@ -366,7 +395,7 @@ public class DBHelper {
ps.setObject(index++, row.get(key)); ps.setObject(index++, row.get(key));
} }
int count = ps.executeUpdate(); int count = ps.executeUpdate();
if(isGeneratedKey){ if (isGeneratedKey) {
close(conn, ps, rs); close(conn, ps, rs);
return count; return count;
} }
...@@ -379,27 +408,30 @@ public class DBHelper { ...@@ -379,27 +408,30 @@ public class DBHelper {
// TODO: handle exception // TODO: handle exception
} catch (Exception e) { } catch (Exception e) {
// TODO: handle exception // TODO: handle exception
} finally{ } finally {
close(conn, ps, rs); close(conn, ps, rs);
} }
return -1; return -1;
} }
} }
/** /**
* 插入一行记录 * 插入一行记录
* @time 2015-07-01 *
* @author renmb
* @param name * @param name
* @param table * @param table
* @param data * @param data
* @return * @return
* @time 2015-07-01
* @author renmb
*/ */
public static int insert(String name, String table, public static int insert(String name, String table,
List<Map<String, Object>> data){ List<Map<String, Object>> data) {
if(name == null || table == null || data == null || data.size() == 0) if (name == null || table == null || data == null || data.size() == 0) {
return -1; return -1;
synchronized(object){ }
synchronized (object) {
String query = null; String query = null;
PreparedStatement ps = null; PreparedStatement ps = null;
Connection conn = null; Connection conn = null;
...@@ -409,7 +441,7 @@ public class DBHelper { ...@@ -409,7 +441,7 @@ public class DBHelper {
Set<String> colums = (data.get(0)).keySet(); Set<String> colums = (data.get(0)).keySet();
query = buildInsertPreparedSQL( query = buildInsertPreparedSQL(
table, colums.toArray( new String[colums.size()])); table, colums.toArray(new String[colums.size()]));
conn = getConnection(name); conn = getConnection(name);
conn.setAutoCommit(false); conn.setAutoCommit(false);
...@@ -440,16 +472,18 @@ public class DBHelper { ...@@ -440,16 +472,18 @@ public class DBHelper {
return -1; return -1;
} }
} }
/** /**
* 更新SQL * 更新SQL
* @time 2015-07-01 *
* @author renmb
* @param name * @param name
* @param query * @param query
* @return * @return
* @time 2015-07-01
* @author renmb
*/ */
public static int update(String name, String query){ public static int update(String name, String query) {
synchronized(object){ synchronized (object) {
PreparedStatement ps = null; PreparedStatement ps = null;
Connection conn = null; Connection conn = null;
try { try {
...@@ -466,15 +500,17 @@ public class DBHelper { ...@@ -466,15 +500,17 @@ public class DBHelper {
return -1; return -1;
} }
} }
/** /**
* 无返回值的SQL * 无返回值的SQL
* @time 2015-07-01 *
* @author renmb
* @param name * @param name
* @param query * @param query
* @time 2015-07-01
* @author renmb
*/ */
public static boolean execute(String name, String query){ public static boolean execute(String name, String query) {
synchronized(object){ synchronized (object) {
PreparedStatement ps = null; PreparedStatement ps = null;
Connection conn = null; Connection conn = null;
try { try {
...@@ -492,29 +528,33 @@ public class DBHelper { ...@@ -492,29 +528,33 @@ public class DBHelper {
return false; return false;
} }
} }
/** /**
* 获取所有结果 * 获取所有结果
* @time 2015-07-01 *
* @author renmb
* @param name * @param name
* @param query * @param query
* @return * @return
* @time 2015-07-01
* @author renmb
*/ */
public static List<Map<String, Object>> fetch(String name, String query){ public static List<Map<String, Object>> fetch(String name, String query) {
return fetch(name, query, true); return fetch(name, query, true);
} }
/** /**
* 获取所有结果 * 获取所有结果
* @time 2015-07-01 *
* @author renmb
* @param name * @param name
* @param query 有返回值的SQL * @param query 有返回值的SQL
* @param byLabel * @param byLabel
* @return * @return
* @time 2015-07-01
* @author renmb
*/ */
public static List<Map<String, Object>> fetch(String name, String query, boolean byLabel){ public static List<Map<String, Object>> fetch(String name, String query, boolean byLabel) {
synchronized(object){ synchronized (object) {
PreparedStatement ps = null; PreparedStatement ps = null;
Connection conn = null; Connection conn = null;
ResultSet rs = null; ResultSet rs = null;
...@@ -555,28 +595,19 @@ public class DBHelper { ...@@ -555,28 +595,19 @@ public class DBHelper {
return null; return null;
} }
} }
/** /**
* 获取首行记录 * 获取首行记录
* @time 2015-07-01 *
* @author renmb
* @param name * @param name
* @param query * @param query
* @param byLabel
* @return * @return
*/
// public static Map<String, Object> first(String name, String query){
// return first(name, query, true);
// }
/**
* 获取首行记录
* @time 2015-07-01 * @time 2015-07-01
* @author renmb * @author renmb
* @param name
* @param query
* @param byLabel
* @return
*/ */
public static Map<String, Object> first(String name, String query, boolean byLabel){ public static Map<String, Object> first(String name, String query, boolean byLabel) {
synchronized(object){ synchronized (object) {
PreparedStatement ps = null; PreparedStatement ps = null;
Connection conn = null; Connection conn = null;
ResultSet rs = null; ResultSet rs = null;
...@@ -589,7 +620,7 @@ public class DBHelper { ...@@ -589,7 +620,7 @@ public class DBHelper {
if (rs.next()) { if (rs.next()) {
ResultSetMetaData rsmd = rs.getMetaData(); ResultSetMetaData rsmd = rs.getMetaData();
int cc = rsmd.getColumnCount(); int cc = rsmd.getColumnCount();
row = new HashMap<String, Object>(); row = new HashMap<String, Object>(10);
for (int i = 1; i <= cc; i++) { for (int i = 1; i <= cc; i++) {
if (byLabel) { if (byLabel) {
coluName = rsmd.getColumnLabel(i); coluName = rsmd.getColumnLabel(i);
...@@ -614,20 +645,22 @@ public class DBHelper { ...@@ -614,20 +645,22 @@ public class DBHelper {
return null; return null;
} }
} }
/** /**
* 某列的最大值 * 某列的最大值
* @time 2015-07-01 *
* @author renmb
* @param name * @param name
* @param table * @param table
* @param column * @param column
* @return * @return
* @time 2015-07-01
* @author renmb
*/ */
public static long max(String name, String table, String column){ public static long max(String name, String table, String column) {
String query = "SELECT MAX(`"+column+"`) AS _maxid FROM "+table; String query = "SELECT MAX(`" + column + "`) AS _maxid FROM " + table;
Map<String, Object> row = first(name, query, true); Map<String, Object> row = first(name, query, true);
if(row == null) if (row == null)
return -1L; return -1L;
try { try {
return (Long) row.get("_maxid"); return (Long) row.get("_maxid");
...@@ -636,20 +669,22 @@ public class DBHelper { ...@@ -636,20 +669,22 @@ public class DBHelper {
} }
return -1L; return -1L;
} }
/** /**
* 某列的最小值 * 某列的最小值
* @time 2015-07-01 *
* @author renmb
* @param name * @param name
* @param table * @param table
* @param column * @param column
* @return * @return
* @time 2015-07-01
* @author renmb
*/ */
public static long min(String name, String table, String column){ public static long min(String name, String table, String column) {
String query = "SELECT MIN(`"+column+"`) AS _minid FROM "+table; String query = "SELECT MIN(`" + column + "`) AS _minid FROM " + table;
Map<String, Object> row = first(name, query, true); Map<String, Object> row = first(name, query, true);
if(row == null) if (row == null)
return -1L; return -1L;
try { try {
return (Long) row.get("_minid"); return (Long) row.get("_minid");
...@@ -658,18 +693,20 @@ public class DBHelper { ...@@ -658,18 +693,20 @@ public class DBHelper {
} }
return -1L; return -1L;
} }
/** /**
* 关闭所有连接池数据 * 关闭所有连接池数据
*/ */
public static synchronized void destroy() { public static synchronized void destroy() {
synchronized(object){ synchronized (object) {
DruidDataSource ds = null; DruidDataSource ds = null;
Set<String> names = POOL.keySet(); Set<String> names = POOL.keySet();
for (String name:names) { for (String name : names) {
try { try {
ds = POOL.get(name); ds = POOL.get(name);
ds.close(); ds.close();
} catch (Exception e) {} } catch (Exception e) {
}
ds = null; ds = null;
POOL.put(name, null); POOL.put(name, null);
} }
...@@ -677,12 +714,13 @@ public class DBHelper { ...@@ -677,12 +714,13 @@ public class DBHelper {
} }
public static synchronized void destroy(String name) { public static synchronized void destroy(String name) {
synchronized(object){ synchronized (object) {
DruidDataSource ds = null; DruidDataSource ds = null;
try { try {
ds = POOL.get(name); ds = POOL.get(name);
ds.close(); ds.close();
} catch (Exception e) {} } catch (Exception e) {
}
ds = null; ds = null;
POOL.put(name, null); POOL.put(name, null);
} }
......
...@@ -37,7 +37,7 @@ public class DateUtil { ...@@ -37,7 +37,7 @@ public class DateUtil {
private static DateFormat zhcnDateTimeFormat = null; private static DateFormat zhcnDateTimeFormat = null;
private static DateFormat zhcnDateStrFormat = null; private static DateFormat zhcnDateStrFormat = null;
public static enum TimeType{ public static enum TimeType {
HOUR_TO_MINUTE HOUR_TO_MINUTE
} }
...@@ -50,46 +50,44 @@ public class DateUtil { ...@@ -50,46 +50,44 @@ public class DateUtil {
} }
//每小时的毫秒数 //每小时的毫秒数
public static int HOUR_MILLI_SECOND = 60 * 60 *1000; public static int HOUR_MILLI_SECOND = 60 * 60 * 1000;
public static int MINUTE_MILLI_SECOND = 60 * 1000; public static int MINUTE_MILLI_SECOND = 60 * 1000;
public static String getDateTime(){ public static String getDateTime() {
DateFormat format = new SimpleDateFormat(TIMEF_FORMAT); DateFormat format = new SimpleDateFormat(TIMEF_FORMAT);
return format.format(System.currentTimeMillis()); return format.format(System.currentTimeMillis());
} }
public static String getDateTime(Date time){
public static String getDateTime(Date time) {
DateFormat format = new SimpleDateFormat(TIMEF_FORMAT); DateFormat format = new SimpleDateFormat(TIMEF_FORMAT);
return format.format(time); return format.format(time);
} }
public static String getDurationTime(long time){
public static String getDurationTime(long time) {
String buffer = ""; String buffer = "";
buffer = ":"+time%1000+"纳秒"; buffer = ":" + time % 1000 + "纳秒";
time = time/1000;//微秒 time = time / 1000;
buffer = ":"+time%1000+"微秒"+buffer; buffer = ":" + time % 1000 + "微秒" + buffer;
time = time/1000;//毫秒 time = time / 1000;
buffer = ":"+time%1000+"毫秒"+buffer; buffer = ":" + time % 1000 + "毫秒" + buffer;
time = time/1000;//毫秒 time = time / 1000;
buffer = ":"+time%60+"秒"+buffer; buffer = ":" + time % 60 + "秒" + buffer;
time = time/60;//秒 time = time / 60;
buffer =time+"分钟"+buffer; buffer = time + "分钟" + buffer;
return buffer; return buffer;
} }
/** /**
*
*
* @author renmb
* @time 2016年10月1日
* @param date * @param date
* @return * @return
* @author renmb
* @time 2016年10月1日
*/ */
public static Date toUTCTimeZone(Date date) { public static Date toUTCTimeZone(Date date) {
try { try {
// TimeZone bjtz = TimeZone.getTimeZone("Asia/Shanghai");
// TimeZone bjtz = TimeZone.getDefault();
TimeZone oldZone = TimeZone.getTimeZone("GMT+08:00"); TimeZone oldZone = TimeZone.getTimeZone("GMT+08:00");
TimeZone newZone = TimeZone.getTimeZone("UTC"); TimeZone newZone = TimeZone.getTimeZone("UTC");
// int timeOffset = oldZone.getRawOffset() - newZone.getRawOffset();
return changeTimeZone(date, oldZone, newZone); return changeTimeZone(date, oldZone, newZone);
} catch (Exception e) { } catch (Exception e) {
...@@ -97,15 +95,16 @@ public class DateUtil { ...@@ -97,15 +95,16 @@ public class DateUtil {
} }
return null; return null;
} }
/** /**
* 时区转换 * 时区转换
* *
* @author renmb
* @time 2016年10月1日
* @param date * @param date
* @param oldZone * @param oldZone
* @param newZone * @param newZone
* @return * @return
* @author renmb
* @time 2016年10月1日
*/ */
public static Date changeTimeZone(Date date, TimeZone oldZone, TimeZone newZone) { public static Date changeTimeZone(Date date, TimeZone oldZone, TimeZone newZone) {
try { try {
...@@ -118,17 +117,12 @@ public class DateUtil { ...@@ -118,17 +117,12 @@ public class DateUtil {
return new Date(localGregorianCalendar2.getTimeInMillis()); return new Date(localGregorianCalendar2.getTimeInMillis());
// Date dateTmp = null;
// if (date != null && oldZone != null && newZone != null) {
// int timeOffset = oldZone.getRawOffset() - newZone.getRawOffset();
// dateTmp = new Date(date.getTime() - timeOffset);
// }
// return dateTmp;
} catch (Exception e) { } catch (Exception e) {
// TODO: handle exception e.printStackTrace();
} }
return date; return date;
} }
/** /**
* @param formatStr * @param formatStr
* @return * @return
...@@ -142,9 +136,9 @@ public class DateUtil { ...@@ -142,9 +136,9 @@ public class DateUtil {
return zhcnDateFormat; return zhcnDateFormat;
} else if (formatStr.equalsIgnoreCase(ZHCN_TIME_FORMAT)) { } else if (formatStr.equalsIgnoreCase(ZHCN_TIME_FORMAT)) {
return zhcnDateTimeFormat; return zhcnDateTimeFormat;
} else if(formatStr.equalsIgnoreCase(DATE_STR_FORMAT)){ } else if (formatStr.equalsIgnoreCase(DATE_STR_FORMAT)) {
return zhcnDateStrFormat; return zhcnDateStrFormat;
}else { } else {
return new SimpleDateFormat(formatStr); return new SimpleDateFormat(formatStr);
} }
} }
...@@ -152,6 +146,7 @@ public class DateUtil { ...@@ -152,6 +146,7 @@ public class DateUtil {
/** /**
* 按照默认formatStr的格式,转化dateTimeStr为Date类型 * 按照默认formatStr的格式,转化dateTimeStr为Date类型
* dateTimeStr必须是formatStr的形式 * dateTimeStr必须是formatStr的形式
*
* @param dateTimeStr * @param dateTimeStr
* @param formatStr * @param formatStr
* @return * @return
...@@ -165,17 +160,15 @@ public class DateUtil { ...@@ -165,17 +160,15 @@ public class DateUtil {
java.util.Date d = sdf.parse(dateTimeStr); java.util.Date d = sdf.parse(dateTimeStr);
return d; return d;
} catch (ParseException e) { } catch (ParseException e) {
//throw new LangException(e); e.printStackTrace();
} }
return null; return null;
} }
public static Date stringToDate(String str) { public static Date stringToDate(String str) {
if (null == str || str.equals("")) if (null == str || str.equals("")) {
return null; return null;
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS"); }
// modify by shizhongwen 2009-05-21 针对香港所传过来的String 如: Wed Feb 23
// 10:12:34 CST 2009
if (0 < str.indexOf("CST")) { if (0 < str.indexOf("CST")) {
try { try {
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US); SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
...@@ -197,11 +190,9 @@ public class DateUtil { ...@@ -197,11 +190,9 @@ public class DateUtil {
public static Date stringToDatetwo(String str) { public static Date stringToDatetwo(String str) {
if (null == str || str.equals("")) if (null == str || str.equals("")) {
return null; return null;
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS"); }
// modify by shizhongwen 2009-05-21 针对香港所传过来的String 如: Wed Feb 23
// 10:12:34 CST 2009
if (0 < str.indexOf("CST")) { if (0 < str.indexOf("CST")) {
try { try {
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US); SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
...@@ -222,10 +213,10 @@ public class DateUtil { ...@@ -222,10 +213,10 @@ public class DateUtil {
} }
public static Date stringToDateThree(String str) { public static Date stringToDateThree(String str) {
if (null == str || str.equals("")) if (null == str || str.equals("")) {
return null; return null;
}
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS"); // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
// modify by shizhongwen 2009-05-21 针对香港所传过来的String 如: Wed Feb 23 // modify by shizhongwen 2009-05-21 针对香港所传过来的String 如: Wed Feb 23
// 10:12:34 CST 2009 // 10:12:34 CST 2009
...@@ -250,13 +241,15 @@ public class DateUtil { ...@@ -250,13 +241,15 @@ public class DateUtil {
/** /**
* 得到几天前的时间 * 得到几天前的时间
* @param d *
* @param date
* @param day 天数 * @param day 天数
* @return * @return
*/ */
public static Date getDateBefore(Date date, int day) { public static Date getDateBefore(Date date, int day) {
if(null == date) if (null == date) {
return null; return null;
}
Calendar now = Calendar.getInstance(); Calendar now = Calendar.getInstance();
now.setTime(date); now.setTime(date);
now.set(Calendar.DATE, now.get(Calendar.DATE) - day); now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
...@@ -272,8 +265,9 @@ public class DateUtil { ...@@ -272,8 +265,9 @@ public class DateUtil {
*/ */
public static Date getDate(Date date, int i) { public static Date getDate(Date date, int i) {
if (null == date) if (null == date) {
return null; return null;
}
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTime(date); calendar.setTime(date);
...@@ -283,40 +277,39 @@ public class DateUtil { ...@@ -283,40 +277,39 @@ public class DateUtil {
} }
public static Date getSystemDate(){ public static Date getSystemDate() {
return Calendar.getInstance().getTime(); return Calendar.getInstance().getTime();
} }
/** /**
* 把日期对象转换成指定格式的字符串 * 把日期对象转换成指定格式的字符串
* *
* @param dDate * @param date - 日期对象
* - 日期对象 * @param sFormat - 日期格式@return String yyyy-MM-dd HH:mm:ss
* @param sFormat
* - 日期格式@return String yyyy-MM-dd HH:mm:ss
*/ */
public static String dateToStr(Date date, String sFormat) { public static String dateToStr(Date date, String sFormat) {
if (null == date) if (null == date) {
return ""; return "";
}
SimpleDateFormat df = new SimpleDateFormat(sFormat); SimpleDateFormat df = new SimpleDateFormat(sFormat);
return df.format(date); return df.format(date);
} }
public static String dateToStrLocal(Date date, String sFormat) { public static String dateToStrLocal(Date date, String sFormat) {
if (null == date) if (null == date) {
return ""; return "";
}
SimpleDateFormat df = new SimpleDateFormat(sFormat,new Locale("US")); SimpleDateFormat df = new SimpleDateFormat(sFormat, new Locale("US"));
return df.format(date); return df.format(date);
} }
/** /**
*得到当前月份的第一天和最后一天 * 得到当前月份的第一天和最后一天
**/ **/
public static String getMonthEndDay(Date date){ public static String getMonthEndDay(Date date) {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
cal.setTime(date); cal.setTime(date);
// 当前月+1 // 当前月+1
...@@ -330,19 +323,19 @@ public class DateUtil { ...@@ -330,19 +323,19 @@ public class DateUtil {
} }
/** /**
* 根据年月得到输入月份的天数 * 根据年月得到输入月份的天数
* */ */
public static int getDays(int m, int n) { public static int getDays(int m, int n) {
int allday; int allday;
int[] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, m); cal.set(Calendar.YEAR, m);
cal.set(Calendar.MONTH, n - 1); cal.set(Calendar.MONTH, n - 1);
cal.set(Calendar.DATE, 1); cal.set(Calendar.DATE, 1);
if ((m % 4 == 0 && m % 100 != 0 || m % 400 == 0) && n == 2) if ((m % 4 == 0 && m % 100 != 0 || m % 400 == 0) && n == 2) {
days[1]++; days[1]++;
}
allday = days[n - 1]; allday = days[n - 1];
return allday; return allday;
...@@ -350,10 +343,11 @@ public class DateUtil { ...@@ -350,10 +343,11 @@ public class DateUtil {
/** /**
* 字符串转Date * 字符串转Date
*
* @param dateStr * @param dateStr
* @return * @return
*/ */
public static Date getStringToDate(String dateStr){ public static Date getStringToDate(String dateStr) {
Date date = new Date(); Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try { try {
...@@ -365,7 +359,7 @@ public class DateUtil { ...@@ -365,7 +359,7 @@ public class DateUtil {
} }
public static Date dateToDate(Date date, String sFormat){ public static Date dateToDate(Date date, String sFormat) {
if (null == date) if (null == date)
return null; return null;
...@@ -380,10 +374,11 @@ public class DateUtil { ...@@ -380,10 +374,11 @@ public class DateUtil {
/** /**
* 获取当月第一天 * 获取当月第一天
* @param sFormat *
* @param date
* @return Date * @return Date
*/ */
public static Date getFirstDay(Date date ){ public static Date getFirstDay(Date date) {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
cal.setTime(date); cal.setTime(date);
cal.set(cal.DATE, 1); cal.set(cal.DATE, 1);
...@@ -392,11 +387,12 @@ public class DateUtil { ...@@ -392,11 +387,12 @@ public class DateUtil {
/** /**
* 获取当月第一天 * 获取当月第一天
*
* @param date * @param date
* @param sFormat * @param sFormat
* @return String date * @return String date
*/ */
public static String getFirstDay(String date,String sFormat ){ public static String getFirstDay(String date, String sFormat) {
try { try {
SimpleDateFormat df = new SimpleDateFormat(sFormat); SimpleDateFormat df = new SimpleDateFormat(sFormat);
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
...@@ -412,11 +408,12 @@ public class DateUtil { ...@@ -412,11 +408,12 @@ public class DateUtil {
/** /**
* 获取当月最后一天 * 获取当月最后一天
*
* @param date * @param date
* @param sFormat * @param sFormat
* @return String date * @return String date
*/ */
public static String getEndDay(String date,String sFormat ){ public static String getEndDay(String date, String sFormat) {
try { try {
SimpleDateFormat df = new SimpleDateFormat(sFormat); SimpleDateFormat df = new SimpleDateFormat(sFormat);
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
...@@ -438,10 +435,11 @@ public class DateUtil { ...@@ -438,10 +435,11 @@ public class DateUtil {
/** /**
* 获取当月最后一天 * 获取当月最后一天
*
* @param date * @param date
* @return date * @return date
*/ */
public static Date getEndDay(Date date ){ public static Date getEndDay(Date date) {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
cal.setTime(date); cal.setTime(date);
// 当前月+1,即下个月 // 当前月+1,即下个月
...@@ -453,12 +451,13 @@ public class DateUtil { ...@@ -453,12 +451,13 @@ public class DateUtil {
return cal.getTime(); return cal.getTime();
} }
public static Date stringToDate(String str,String format) {
public static Date stringToDate(String str, String format) {
if (null == str || str.equals("")) if (null == str || str.equals(""))
return null; return null;
if(format==null || format.equals("")){ if (format == null || format.equals("")) {
format="yyyy-MM-dd HH:mm:SS"; format = "yyyy-MM-dd HH:mm:SS";
} }
SimpleDateFormat sdf = new SimpleDateFormat(format); SimpleDateFormat sdf = new SimpleDateFormat(format);
...@@ -474,12 +473,15 @@ public class DateUtil { ...@@ -474,12 +473,15 @@ public class DateUtil {
/** /**
* date 为指定时间 2012-12-12 14:23:00,N为获取时间为N小时之后的时间 * date 为指定时间 2012-12-12 14:23:00,N为获取时间为N小时之后的时间
*
* @param date * @param date
* @param n * @param n
* @return * @return
*/ */
public static Date getDateAffterHour(Date date,int n) { public static Date getDateAffterHour(Date date, int n) {
if(null == date) return null; if (null == date) {
return null;
}
Calendar c = Calendar.getInstance(); Calendar c = Calendar.getInstance();
c.setTimeInMillis(date.getTime() + n * DateUtil.HOUR_MILLI_SECOND); c.setTimeInMillis(date.getTime() + n * DateUtil.HOUR_MILLI_SECOND);
return c.getTime(); return c.getTime();
...@@ -487,20 +489,24 @@ public class DateUtil { ...@@ -487,20 +489,24 @@ public class DateUtil {
/** /**
* date 为指定时间 2012-12-12 14:23:00,N为获取时间为N小时之后的时间 * date 为指定时间 2012-12-12 14:23:00,N为获取时间为N小时之后的时间
*
* @param date * @param date
* @param n * @param n
* @return * @return
*/ */
public static Date getDateAffterMinute(Date date,int n) { public static Date getDateAffterMinute(Date date, int n) {
if(null == date) return null; if (null == date) {
return null;
}
Calendar c = Calendar.getInstance(); Calendar c = Calendar.getInstance();
c.setTimeInMillis(date.getTime() + n * DateUtil.MINUTE_MILLI_SECOND); c.setTimeInMillis(date.getTime() + n * DateUtil.MINUTE_MILLI_SECOND);
return c.getTime(); return c.getTime();
} }
public static Date stringToDateHH(String str) { public static Date stringToDateHH(String str) {
if (null == str || str.equals("")) if (null == str || str.equals("")) {
return null; return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
try { try {
return sdf.parse(str); return sdf.parse(str);
...@@ -510,10 +516,12 @@ public class DateUtil { ...@@ -510,10 +516,12 @@ public class DateUtil {
} }
} }
public static Date dateToDateFormat(Date date,String format){ public static Date dateToDateFormat(Date date, String format) {
if(null == date) return null; if (null == date) {
if(format==null || format.equals("")){ return null;
format="yyyy-MM-dd HH:mm:SS"; }
if (format == null || format.equals("")) {
format = "yyyy-MM-dd HH:mm:SS";
} }
SimpleDateFormat df = new SimpleDateFormat(format, Locale.CHINA); SimpleDateFormat df = new SimpleDateFormat(format, Locale.CHINA);
...@@ -535,11 +543,11 @@ public class DateUtil { ...@@ -535,11 +543,11 @@ public class DateUtil {
* @param destPattern 要转换成的日期格式 * @param destPattern 要转换成的日期格式
* @return * @return
*/ */
public static String transferDate(String date,String oriPattern,String destPattern){ public static String transferDate(String date, String oriPattern, String destPattern) {
if(StringUtils.isBlank(date)){ if (StringUtils.isBlank(date)) {
return ""; return "";
} }
SimpleDateFormat sdf = (SimpleDateFormat)SimpleDateFormat.getDateInstance(0,Locale.ENGLISH); SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance(0, Locale.ENGLISH);
sdf.applyPattern(oriPattern); sdf.applyPattern(oriPattern);
try { try {
...@@ -549,26 +557,32 @@ public class DateUtil { ...@@ -549,26 +557,32 @@ public class DateUtil {
return sdf.format(parse); return sdf.format(parse);
} catch (ParseException e) { } catch (ParseException e) {
e.printStackTrace(); e.printStackTrace();
} } finally {
finally{
sdf = null; sdf = null;
} }
return ""; return "";
} }
/** /**
* 获得 * 获得
*
* @param date * @param date
* @param format * @param format
* @param num 获得num个月之后的日期 * @param num 获得num个月之后的日期
* @return * @return
*/ */
public static String getNextMonth(String date,String format,Integer num){ public static String getNextMonth(String date, String format, Integer num) {
try { try {
SimpleDateFormat sdf = new SimpleDateFormat(format);//格式化对象 //格式化对象
Calendar calendar = Calendar.getInstance();//日历对象 SimpleDateFormat sdf = new SimpleDateFormat(format);
calendar.setTime(sdf.parse(date));//设置当前日期 //日历对象
calendar.add(Calendar.MONTH, num);//月份加num Calendar calendar = Calendar.getInstance();
return sdf.format(calendar.getTime());//输出格式化的日期 //设置当前日期
calendar.setTime(sdf.parse(date));
//月份加num
calendar.add(Calendar.MONTH, num);
//输出格式化的日期
return sdf.format(calendar.getTime());
} catch (ParseException e) { } catch (ParseException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
...@@ -598,7 +612,7 @@ public class DateUtil { ...@@ -598,7 +612,7 @@ public class DateUtil {
* @param date * @param date
* @return true:是|false:不是 * @return true:是|false:不是
*/ */
public static boolean isFirstDayOfMonth(Date date){ public static boolean isFirstDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTime(date); calendar.setTime(date);
if (calendar.get(Calendar.DAY_OF_MONTH) == 1) { if (calendar.get(Calendar.DAY_OF_MONTH) == 1) {
...@@ -609,22 +623,23 @@ public class DateUtil { ...@@ -609,22 +623,23 @@ public class DateUtil {
/** /**
* 获得日期的年月 * 获得日期的年月
*
* @param date * @param date
* @param format * @param format
* @return 返回的年月格式为 yyyyMM 例如:201504 * @return 返回的年月格式为 yyyyMM 例如:201504
*/ */
public static String getYearMonth(String date,String format){ public static String getYearMonth(String date, String format) {
try { try {
String yyyyMM=""; String yyyyMM = "";
SimpleDateFormat sdf = new SimpleDateFormat(format);//格式化对象 SimpleDateFormat sdf = new SimpleDateFormat(format);//格式化对象
Calendar cal=Calendar.getInstance();//使用日历类 Calendar cal = Calendar.getInstance();//使用日历类
cal.setTime(sdf.parse(date)); cal.setTime(sdf.parse(date));
int year=cal.get(Calendar.YEAR);//得到年 int year = cal.get(Calendar.YEAR);//得到年
int month=cal.get(Calendar.MONTH)+1;//得到月,因为从0开始的,所以要加1 int month = cal.get(Calendar.MONTH) + 1;//得到月,因为从0开始的,所以要加1
if(month<10){//月份格式 yyyyMM if (month < 10) {//月份格式 yyyyMM
yyyyMM= year+"0"+month; yyyyMM = year + "0" + month;
}else{ } else {
yyyyMM=year+""+month; yyyyMM = year + "" + month;
} }
return yyyyMM; return yyyyMM;
} catch (ParseException e) { } catch (ParseException e) {
...@@ -635,13 +650,14 @@ public class DateUtil { ...@@ -635,13 +650,14 @@ public class DateUtil {
/** /**
* 获取date + offset 日期加上offset偏移天数凌晨的时间 * 获取date + offset 日期加上offset偏移天数凌晨的时间
* @param Date date 日期 *
* @param int offset 时间偏移量 * @param date 日期
* @param offset 时间偏移量
* @return * @return
* @author panjianlin * @author panjianlin
* @date 2015-09-08 * @date 2015-09-08
*/ */
public static Date getOffsetDawn(Date date,int offset){ public static Date getOffsetDawn(Date date, int offset) {
Date offsetDate = offsetDate(date, offset); Date offsetDate = offsetDate(date, offset);
String dateStr = dateFormat.format(offsetDate); String dateStr = dateFormat.format(offsetDate);
String dateTimeStr = dateStr + " 00:00:00"; String dateTimeStr = dateStr + " 00:00:00";
...@@ -657,14 +673,15 @@ public class DateUtil { ...@@ -657,14 +673,15 @@ public class DateUtil {
/** /**
* 获取date + offset 日期加上offset偏移天数的时间 * 获取date + offset 日期加上offset偏移天数的时间
* @param Date date 日期 *
* @param int offset 时间偏移量 * @param date 日期
* @param String subTime 小时到秒的时间字符串 如 " 11:59:15" * @param offset 时间偏移量
* @param subTime 小时到秒的时间字符串 如 " 11:59:15"
* @return * @return
* @author panjianlin * @author panjianlin
* @date 2015-09-08 * @date 2015-09-08
*/ */
public static Date getOffsetDate(Date date,int offset,String subTime){ public static Date getOffsetDate(Date date, int offset, String subTime) {
Date offsetDate = offsetDate(date, offset); Date offsetDate = offsetDate(date, offset);
String dateStr = dateFormat.format(offsetDate); String dateStr = dateFormat.format(offsetDate);
String dateTimeStr = dateStr + subTime; String dateTimeStr = dateStr + subTime;
...@@ -680,13 +697,14 @@ public class DateUtil { ...@@ -680,13 +697,14 @@ public class DateUtil {
/** /**
* 获取date + offset 日期加上offset偏移天数的时间 * 获取date + offset 日期加上offset偏移天数的时间
* @param Date date 日期 *
* @param int offset 时间偏移量 * @param date 日期
* @param offset 时间偏移量
* @return Date * @return Date
* @author panjianlin * @author panjianlin
* @date 2015-09-08 * @date 2015-09-08
*/ */
public static Date offsetDate(Date date,int offset){ public static Date offsetDate(Date date, int offset) {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
//转换成Calendar类型 //转换成Calendar类型
cal.setTime(date); cal.setTime(date);
...@@ -699,13 +717,14 @@ public class DateUtil { ...@@ -699,13 +717,14 @@ public class DateUtil {
/** /**
* 获取date + offset 日期加上offset偏移分钟数 * 获取date + offset 日期加上offset偏移分钟数
* @param Date date 日期 *
* @param int offset 时间偏移量 * @param date 日期
* @param offset 时间偏移量
* @return Date * @return Date
* @author panjianlin * @author panjianlin
* @date 2015-09-08 * @date 2015-09-08
*/ */
public static Date offsetMinute(Date date,int offset){ public static Date offsetMinute(Date date, int offset) {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
//转换成Calendar类型 //转换成Calendar类型
cal.setTime(date); cal.setTime(date);
...@@ -716,27 +735,23 @@ public class DateUtil { ...@@ -716,27 +735,23 @@ public class DateUtil {
return goalDate; return goalDate;
} }
public static void main(String args[]){
System.out.println(offsetMinute(new Date(), -10));
}
/** /**
* 取日期字符串 * 取日期字符串
* @param atd *
* @param date
* @param timeType 时间段 比如hh:mm则为枚举型 HOUR_TO_MINUTE * @param timeType 时间段 比如hh:mm则为枚举型 HOUR_TO_MINUTE
* @return * @return
*/ */
public static String splitDateToStrSub(Date date, TimeType timeType) { public static String splitDateToStrSub(Date date, TimeType timeType) {
String dateSubStr = null; String dateSubStr = null;
if(date == null){ if (date == null) {
return null; return null;
} }
String dateStr = dateToStr(date,TIMEF_FORMAT); String dateStr = dateToStr(date, TIMEF_FORMAT);
if(timeType == TimeType.HOUR_TO_MINUTE){ if (timeType == TimeType.HOUR_TO_MINUTE) {
dateSubStr = dateStr.substring(11, 16); dateSubStr = dateStr.substring(11, 16);
} }
...@@ -747,19 +762,20 @@ public class DateUtil { ...@@ -747,19 +762,20 @@ public class DateUtil {
* 从一种日期格式转换到另一种日期格式 * 从一种日期格式转换到另一种日期格式
* 比如 2015-01-02 12:01:21 ----- 2015-01-02 * 比如 2015-01-02 12:01:21 ----- 2015-01-02
* 或 2015-01-02 ---- 2015/01/02 * 或 2015-01-02 ---- 2015/01/02
*
* @param date * @param date
* @param format * @param format
* @return * @return
*/ */
public static Date getDateToDate(Date date, String format) { public static Date getDateToDate(Date date, String format) {
Date tdate = null; Date tdate = null;
if(date == null){ if (date == null) {
return null; return null;
} }
try{ try {
DateFormat sdf = getDateFormat(format); DateFormat sdf = getDateFormat(format);
date = sdf.parse(sdf.format(date)); date = sdf.parse(sdf.format(date));
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
...@@ -768,5 +784,4 @@ public class DateUtil { ...@@ -768,5 +784,4 @@ public class DateUtil {
} }
} }
...@@ -352,10 +352,12 @@ public class Util { ...@@ -352,10 +352,12 @@ public class Util {
if(workPhone == null || workPhone.length() == 0) if(workPhone == null || workPhone.length() == 0)
return workPhone; return workPhone;
try { try {
workPhone = workPhone.replaceAll("[^\\d|+]+", ""); System.out.println(workPhone + ":格式化不匹配,#");
if(workPhone.matches("0+")){ // 非座机号设置为空 workPhone = workPhone.replaceAll("[^\\d^,^#|+]+", "");
// 非座机号设置为空
if (workPhone.matches("0+")) {
workPhone = ""; workPhone = "";
} else if(workPhone.startsWith("0") == false){ // 非0开头的号码需要处理 } else if (workPhone.startsWith("0") == false) {
if(workPhone.startsWith("1") && workPhone.length() == 11){// 非座机号,是手机号,将号码处理为空 if(workPhone.startsWith("1") && workPhone.length() == 11){// 非座机号,是手机号,将号码处理为空
workPhone = ""; workPhone = "";
...@@ -380,8 +382,10 @@ public class Util { ...@@ -380,8 +382,10 @@ public class Util {
} else if(workPhone.startsWith("+")){// 4、+ xxxx xxxx -> 000 xxxx xxxx 北京号码,去掉+号,加拨000 } else if(workPhone.startsWith("+")){// 4、+ xxxx xxxx -> 000 xxxx xxxx 北京号码,去掉+号,加拨000
workPhone = workPhone.replace("+", "000"); workPhone = workPhone.replace("+", "000");
} else {// 5、xxx xxxx xxxx -> 0 xxx xxxx xxxx 国内非北京号码,加拨0 } else if (workPhone.indexOf(",") == 1 & workPhone.indexOf("#") == 1) {
workPhone = workPhone;
} else { // 5、xxx xxxx xxxx -> 0 xxx xxxx xxxx 国内非北京号码,加拨0
workPhone = "0"+workPhone; workPhone = "0"+workPhone;
} }
return workPhone; return workPhone;
...@@ -633,4 +637,9 @@ public class Util { ...@@ -633,4 +637,9 @@ public class Util {
// } // }
// System.out.println(Util.updateGroupAvatar("4433", "793289947956154368")); // System.out.println(Util.updateGroupAvatar("4433", "793289947956154368"));
// } // }
public static void main(String[] args) {
Util util = new Util();
System.out.println(Util.formatedWorkPhone("656521"));
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment