今天给大家分享一下我自己比较常用的时间工具类和字符串工具类,主要提供了一些比较常用的方法,比如日期转标准格式字符串,字符串转日期,字符串的截取、转换、验证身份证、手机号等等常用方法,不多说,直接贴代码。
public class DateUtils { /** * 标准时间格式字符串 "yyyy-MM-dd HH:mm:ss" */ public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** * 将日期转换为标准格式字符串 "yyyy-MM-dd HH:mm:ss" * * @param milliSeconds * 毫秒数 * @return 标准格式字符串 */ public static String formatDateToDefaultStr(long milliSeconds) { return formatDate(milliSeconds, DEFAULT_DATE_FORMAT); } /** * 将日期转换为标准格式字符串 "yyyy-MM-dd HH:mm:ss" * * @param Date * date * @return 标准格式字符串 */ public static String formatDateToDefaultStr(Date date) { return formatDate(date, DEFAULT_DATE_FORMAT); } /** * 将日期转换为指定格式字符串 * * @param milliSeconds * 毫秒数 * @return 标准格式字符串 */ public static String formatDate(long milliSeconds, String dateFormat) { String dateStr = ""; if (milliSeconds != 0) { dateStr = formatDate(new Date(milliSeconds), dateFormat); } return dateStr; } /** * 根据输入格式转换为时间字符串 * * @param date * @param dateFormat * @return */ public static String formatDate(Date date, String dateFormat) { if (date == null || "".equals(date)) { return ""; } return new SimpleDateFormat(dateFormat).format(date); } /** * 将标准字符串转换为日期对象 * * @param dateStr * 日期字符串 * @param dateFormat * 日期格式 * @return 日期对象 */ public static Date convertToDate(String dateStr, String dateFormat) { if (!StringUtils.isEmpty(dateStr)) { try { return new SimpleDateFormat(dateFormat).parse(dateStr); } catch (ParseException e) { logger.error(e.getMessage()); e.printStackTrace(); } } return null; } /** * 将指定格式字符串转换为日期对象 * * @param dateStr * 日期字符串 * @return 日期对象 */ public static Date convertToDate(String dateStr) { return convertToDate(dateStr, DEFAULT_DATE_FORMAT); } /** * 将标准字符串转换为毫秒 * * @param dateStr * 日期字符串 * @return 毫秒数 */ public static long convertToMilliSeconds(String dateStr) { return convertToDate(dateStr).getTime(); } /** * 将指定格式字符串转换为毫秒 * * @param dateStr * 日期字符串 * @param dateFormat * 日期格式 * @return 毫秒数 */ public static long convertToMilliSeconds(String dateStr, String dateFormat) { return convertToDate(dateStr, dateFormat).getTime(); } /** * @return 当前系统毫秒数 */ public static long now() { return System.currentTimeMillis(); } }JS的时间转字符串(yyyy-mm-dd hh:mi"ss)
function formatDate (date, fmt) { var mtDate = new Date(date); // 拼配fmt中的一个或多个y字符 if (/(y+)/.test(fmt)) { // 匹配成功 // RegExp.$1是匹配的y字符('yyyy'), 用时间的年份替换 fmt = fmt.replace(RegExp.$1, (mtDate.getFullYear() + '').substr(4 - RegExp.$1.length)); // substr() 方法可在字符串中抽取从 start 下标开始的指定数目的字符。 } var o = { 'M+': mtDate.getMonth() + 1, // getMouth()获取的月份是从0~11,按习惯+1 'd+': mtDate.getDate(), 'h+': mtDate.getHours(), 'm+': mtDate.getMinutes(), 's+': mtDate.getSeconds() }; for (var key in o) { if (new RegExp('('+key+')').test(fmt)) { var str = o[key] + ''; // 时间对象对应的真实数字,转为字符串 + ‘’ // 将字符串的MM dd hh mm 替换掉 fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str)); } } return fmt; } //日期补0 function padLeftZero (str) { return ('00' + str).substr(str.length); }字符串工具类
public class StringUtils { private static final int[] wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 }; private static final int[] vi = { 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 }; private static int[] ai = new int[18]; /** * 判断字符串是否为空 * * @param string 设置字符串 * @return boolean 返回是否为空 */ public static boolean isEmpty(String string) { return string == null || string.length() == 0; } /** * 判断两个字符串是否值相等 * * @param a 设置第一个字符串 * @param b 设置第二个字符串 * @return boolean 返回比较的结果 */ public static boolean compare(String a, String b) { if (isEmpty(a) && isEmpty(b)) return true; if (!isEmpty(a) && !isEmpty(b)) return a.equals(b); else return false; } /** * 判断两个字符串是否值相等,忽略大小写 * * @param a 设置第一个字符串 * @param b 设置第二个字符串 * @return boolean 返回比较的结果 */ public static boolean compareIgnoreCase(String a, String b) { if (isEmpty(a) && isEmpty(b)) return true; if (!isEmpty(a) && !isEmpty(b)) return a.equalsIgnoreCase(b); else return false; } /** * 复制字符串中从开始到指定的位置 * * @param src 设置字符串 * @param len 指定复制到某个位置 * @return String 返回结果 */ public static String copy(String src, int len) { if (src == null) return null; if (src.length() > len) return len <= 0 ? null : src.substring(0, len); else return src; } /** * 删除字符串中指定的一段字符串内容 * * @param src 设置原字符串 * @param delStr 设置需要删除的字符串 * @return String 返回结果 */ public static String delete(String src, String delStr) { if (isEmpty(src) || isEmpty(delStr)) return src; StringBuffer buffer = new StringBuffer(src); for (int index = src.length(); (index = src.lastIndexOf(delStr, index)) >= 0; index -= delStr.length()) buffer.delete(index, index + delStr.length()); return buffer.toString(); } /** * 将指定的字符和位置插入到原字符串中 * * @param src 设置原字符串 * @param anotherStr 设置需要插入的字符串 * @param offset 位置 * @return String 返回结果 */ public static String insert(String src, String anotherStr, int offset) { if (isEmpty(src) || isEmpty(anotherStr)) return src; StringBuffer buffer = new StringBuffer(src); if (offset >= 0 && offset <= src.length()) buffer.insert(offset, anotherStr); return buffer.toString(); } /** * 追加指定的字符串到原字符串中 * * @param src 设置原字符串 * @param appendStr 设置需要追加的字符串 * @return String 返回结果 */ public static String append(String src, String appendStr) { if (isEmpty(src) || isEmpty(appendStr)) { return src; } else { StringBuffer buffer = new StringBuffer(src); buffer.append(appendStr); return buffer.toString(); } } /** * 根据参数替换字符串内容功能 * * @param src 设置原字符串 * @param oldStr 指定替换字符串 * @param newStr 将要替换的内容 * @param isCaseSensitive 是否区分大小写 * @return String 返回结果 */ public static String replace(String src, String oldStr, String newStr, boolean isCaseSensitive) { if (isEmpty(src) || isEmpty(oldStr) || newStr == null) return src; String s = isCaseSensitive ? src : src.toLowerCase(); String o = isCaseSensitive ? oldStr : oldStr.toLowerCase(); StringBuffer buffer = new StringBuffer(src); for (int index = s.length(); (index = s.lastIndexOf(o, index)) >= 0; index -= o.length()) buffer.replace(index, index + o.length(), newStr); return buffer.toString(); } /** * 根据参数替换字符串内容功能,可指定位置 * * @param src 设置原字符串 * @param oldStr 指定替换字符串 * @param newStr 将要替换的内容 * @param isCaseSensitive 是否区分大小写 * @param index 指定位置 * @return String 返回结果 */ public static String replace(String src, String oldStr, String newStr, boolean isCaseSensitive, int index) { if (src == null || src.length() == 0 || oldStr == null || oldStr.length() == 0 || index <= 0) return src; if (newStr == null) newStr = ""; String s = isCaseSensitive ? src : src.toLowerCase(); String old = isCaseSensitive ? oldStr : oldStr.toLowerCase(); StringBuffer buffer = new StringBuffer(src); int length = old.length(); int pos; for (pos = s.indexOf(old, 0); pos >= 0; pos = s.indexOf(old, pos + length)) if (--index == 0) break; if (pos >= 0 && index == 0) buffer.replace(pos, pos + length, newStr); return buffer.toString(); } /** * 给传入的字符串前后加双引号 * * @param str 设置原字符串 * @return String 返回结果 */ public static String quote(String str) { if (isEmpty(str)) return "\"\""; StringBuffer buffer = new StringBuffer(str); if (!str.startsWith("\"")) buffer.insert(0, "\""); if (!str.endsWith("\"")) buffer.append("\""); return buffer.toString(); } /** * 去除字符串中的双引号 * * @param str 设置原字符串 * @return String 返回结果 */ public static String extractQuotedStr(String str) { if (isEmpty(str)) return str; StringBuffer buffer = new StringBuffer(str); int index = str.length(); while (buffer.charAt(buffer.length() - 1) == '"') { buffer.deleteCharAt(buffer.length() - 1); index = buffer.length(); if (index <= 0) break; } if (buffer.length() == 0) return ""; while (buffer.charAt(0) == '"') { buffer.deleteCharAt(0); index = buffer.length(); if (index <= 0) break; } return buffer.toString(); } /** * 截取字符串中到指定的字符的内容,从左边开始 * * @param str 设置原字符串 * @param c 设置指定字符 * @return String 返回结果 */ public static String strChar(String str, char c) { if (str == null || str.length() == 0) return null; for (int i = 0; i < str.length(); i++) if (str.charAt(i) == c) return str.substring(i); return null; } /** * 截取字符串中到指定的字符的内容,从右边开始 * * @param str 设置原字符串 * @param c 设置指定字符 * @return String 返回结果 */ public static String strRChar(String str, char c) { if (str == null || str.length() == 0) return null; for (int i = str.length() - 1; i >= 0; i--) if (str.charAt(i) == c) return str.substring(i); return null; } /** * 将Object对象数组转成字符串数组 * * @param array 设置Object对象数组 * @return String[] 返回结果 */ public static String[] toArray(Object array[]) { if (array == null || array.length == 0) return null; String result[] = new String[array.length]; for (int i = 0; i < array.length; i++) if (array[i] != null) result[i] = array[i].toString(); return result; } /** * 将字符串数组复制到LIST中 * * @param array 设置字符串数组 * @param list 设置LIST集合对象 * @param index 设置复制到LIST位置 * @return List 返回结果 */ public static List copyToList(String array[], List list, int index) { if (array == null || array.length == 0) return list; if (list == null || index < 0) return list; for (int i = 0; i < array.length; i++) if (list.size() <= i + index) list.add(index + i, array[i]); else list.set(index + i, array[i]); return list; } /** * 验证是否为电子邮件格式 * * @param theEmail 设置电子邮件地址字符串 * @return boolean 返回是否合法 */ public static boolean isValidEmail(String theEmail) { boolean isEmail = false; try { String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"; Pattern regex = Pattern.compile(check); Matcher matcher = regex.matcher(theEmail); boolean isMatched = matcher.matches(); if (isMatched) { isEmail = true; } } catch (Exception e) { e.printStackTrace(); return isEmail; } return isEmail; } /** * 去除字符串左边空格 * * @param str 设置原字符串 * @return String 返回结果 */ public static String trimLeft(String str) { if (str == null) return null; int length = str.length(); if (length == 0) return ""; StringBuffer buffer = new StringBuffer(str); int index; for (index = 0; index < length && buffer.charAt(index) == ' '; index++) ; if (index == length) return ""; else return buffer.substring(index); } /** * 去除字符串右边空格 * * @param str 设置原字符串 * @return String 返回结果 */ public static String trimRight(String str) { if (str == null) return null; int length = str.length(); if (length == 0) return ""; StringBuffer buffer = new StringBuffer(str); int index; for (index = length - 1; index >= 0 && buffer.charAt(index) == ' '; index--) ; if (index < 0 && buffer.charAt(0) == ' ') return ""; else return buffer.substring(0, index + 1); } /** * 验证身份证的合法性 * * @param idcard 设置身份证字符串 * @return boolean 返回结果 */ public static boolean idCardVerify(String idcard) { if (idcard.length() == 15) { idcard = idCardUptoeighteen(idcard); } if (idcard.length() != 18) { return false; } String verify = idcard.substring(17, 18); if (verify.equals(getIdCardVerify(idcard))) { return true; } return false; } /** * 获得身份证的合法性 * * @param eightcardid 设置身份证字符串 * @return String 返回结果 */ public static String getIdCardVerify(String eightcardid) { int remaining = 0; if (eightcardid.length() == 18) { eightcardid = eightcardid.substring(0, 17); } if (eightcardid.length() == 17) { int sum = 0; for (int i = 0; i < 17; i++) { String k = eightcardid.substring(i, i + 1); ai[i] = Integer.parseInt(k); } for (int i = 0; i < 17; i++) { sum = sum + wi[i] * ai[i]; } remaining = sum % 11; } return remaining == 2 ? "X" : String.valueOf(vi[remaining]); } /** * 获得身份证15转18位 * * @param fifteencardid 设置身份证字符串 * @return String 返回结果 */ public static String idCardUptoeighteen(String fifteencardid) { if (fifteencardid.length() != 15) return null; String eightcardid = fifteencardid.substring(0, 6); eightcardid = eightcardid + "19"; eightcardid = eightcardid + fifteencardid.substring(6, 15); eightcardid = eightcardid + getIdCardVerify(eightcardid); return eightcardid; } /** * 验证电话号码合法格式,格式为02584555112 * * @param phoneCode 设置电话号码字符串 * @return boolean 返回结果 */ public static boolean isPhoneNum(String phoneCode) { Pattern p = Pattern.compile("[0][1-9]{2,3}[1-9]{6,8}"); Matcher m = p.matcher(phoneCode); boolean b = m.matches(); return b; } /** * 字符数组转换为字符串,用逗号隔开 * @param str * @return */ public static String arrayToString(String[] str) { if (str == null) return ""; StringBuffer rStr = new StringBuffer(""); for (int i = 0; i < str.length; i++) { rStr.append(str[i]); rStr.append(","); } // 截取逗号 if (rStr.toString().length() > 0) { rStr.setLength(rStr.length() - 1); } return rStr.toString(); } /** * 将字符串集合转成逗号分隔的长字符串 * @param strList * @return */ public static String parseListToString(List<String> strList) { if (strList == null || strList.size() == 0) { return ""; } StringBuilder urlStr = new StringBuilder(); for (String url : strList) { urlStr.append("'" + url + "'" + ","); } return urlStr.substring(0, urlStr.length() - 1); } }