Commit 9dc0393b by java-李谡

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

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