import java.text.DecimalFormat; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.Random; import java.util.StringTokenizer; import java.util.Vector; public class DateUtil { public static final String DEFAULT_DATE_FORMAT = "MM-dd-yyyy"; public static final String ZH_DATE_FORMAT = "yyyy-MM-dd"; public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss"; public static final String DEFAULT_DATETIME_FORMAT = "MM-dd-yyyy HH:mm:ss"; public static final String ZH_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; public static final String DEFAULT_PRECISION_DATETIME_FORMAT = "MM-dd-yyyy HH:mm:ss:SSS"; public static final String ZH_PRECISION_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss:SSS"; public static final String DEFAULT_PRECISION_MILLTIME_FORMAT = "yyyy:MM:dd HH:mm:ss:SSS"; public static final String DEFAULT_HOUR_DATE_FORMAT = "MM-dd-yyyy HH"; public static final String ZH_HOUR_DATE_FORMAT = "yyyy-MM-dd HH"; public static final String DEFAULT_MINUTE_DATE_FORMAT = "MM-dd-yyyy HH:mm"; public static final String ZH_MINUTE_DATE_FORMAT = "yyyy-MM-dd HH:mm"; public static final String ZH_SECOND_DATE_FORMAT = "yyyyMMddHHmmss"; /** * 日期时间格式1-"yyyy.MM.dd HH:mm:ss" */ public static final String TIMEFORMAT_FULL = "yyyy.MM.dd HH:mm:ss"; /** * 日期时间格式2-"yyyy.MM.dd HH:mm" */ public static final String TIMEFORMAT_NO_SEC = "yyyy.MM.dd HH:mm"; /** * 日期格式1-"yyyy.MM.dd" */ public static final String TIMEFORMAT_NO_TIME = "yyyy.MM.dd"; /** * 日期格式2-"yyyy.MM" */ public static final String TIMEFORMAT_YEAR_MONTH_ONLY = "yyyy.MM"; /** * 日期格式3-"yyyyMMdd" */ public static final String TIMEFORMAT_ANOTHER_DATE = "yyyyMMdd"; /** * 1024以内的素数表,172个 */ public static int sNumprime[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021 }; /** * 构造函数 */ public DateUtil() { } /** * 按日期时间格式1返回当前时间 yyyy.MM.dd HH:mm:ss * * @return String 获得当前时间 */ public static String getCurrentDateTime() { SimpleDateFormat sdf = new SimpleDateFormat(TIMEFORMAT_FULL); return sdf.format(new Date()); } public static String getCurrentDateTime_14() { SimpleDateFormat sdf = new SimpleDateFormat(ZH_SECOND_DATE_FORMAT); return sdf.format(new Date()); } /** * 按日期格式1返回当前日期 * * @return String 获得当前日期 */ public static String getCurrentDate() { SimpleDateFormat sdf = new SimpleDateFormat(TIMEFORMAT_NO_TIME, Locale.US); return sdf.format(new Date()); } /** * 按日期格式3返回数字日期 * * @return String 获得数字日期 */ public static String getPiciDate() { SimpleDateFormat sdf = new SimpleDateFormat(TIMEFORMAT_ANOTHER_DATE, Locale.US); return sdf.format(new Date()); } /** * 按日期格式3返回数字日期 * * @param sNowDateTime 设置时间,格式为YYYYMMDDHH24MISS */ public static void setCurrentDate(String sNowDateTime) { if (sNowDateTime.length() == 14) { int iyear; int imonth; int idate; int ihour; int iminute; int isecond; iyear = java.lang.Integer.parseInt(sNowDateTime.substring(0, 4)); if (iyear < 2000) { iyear = 2003; } imonth = java.lang.Integer.parseInt(sNowDateTime.substring(4, 6)); if (imonth > 12) { imonth = 11; } idate = java.lang.Integer.parseInt(sNowDateTime.substring(6, 8)); if (idate > 31) { idate = 11; } ihour = java.lang.Integer.parseInt(sNowDateTime.substring(8, 10)); if (ihour > 23) { ihour = 11; } iminute = java.lang.Integer.parseInt(sNowDateTime.substring(10, 12)); if (iminute > 59) { iminute = 11; } isecond = java.lang.Integer.parseInt(sNowDateTime.substring(12, 14)); if (isecond > 59) { isecond = 11; } Calendar serverNow = Calendar.getInstance(); serverNow.set(iyear, imonth, idate, ihour, iminute, isecond); } } /** * Function name: sGetAddTimes Description: 给一个时间增加上一定的时间 * * @param timePoint 计时时间点(格式:TimeFormat1) * @param addSeconds times to add(单位:秒) * @return String 返回增加时间后的时间(格式:TimeFormat1) */ public static String sGetAddTimes(String timePoint, long addSeconds) { if (timePoint.length() == 19) { String dRet = ""; SimpleDateFormat sdf = new SimpleDateFormat(TIMEFORMAT_FULL); Date timePoints = sdf.parse(timePoint, new java.text.ParsePosition(0)); Date dateTimes = new Date((timePoints.getTime() / 1000L + (addSeconds)) * 1000L); dRet = sdf.format(dateTimes); return dRet; } else { return ""; } } /** * Function name: sGetAddTimes Description: 给一个时间减去上一定的时间 * * @param timePoint 计时时间点(格式:TimeFormat1) * @param addSeconds times to add(单位:秒) * @return String 返回减去时间后的时间(格式:TimeFormat1) */ public static String sGetMinusTimes(String timePoint, long minusSeconds) { if (timePoint.length() == 19) { String dRet = ""; SimpleDateFormat sdf = new SimpleDateFormat(TIMEFORMAT_FULL); Date timePoints = sdf.parse(timePoint, new java.text.ParsePosition(0)); Date dateTimes = new Date((timePoints.getTime() / 1000L - (minusSeconds)) * 1000L); dRet = sdf.format(dateTimes); return dRet; } else { return ""; } } /** * Function name: lTimeCompare Description: 两时间比较. Compare two times * * @param compTime1 比较时间1(格式:TimeFormat1) * @param compTime2 比较时间2(格式:TimeFormat1) * @return long 返回相差的时间(单位:秒) */ public static long lTimeCompare(String compTime1, String compTime2) { if ((compTime1.length() == 19) && (compTime2.length() == 19)) { long iReturn = -1; SimpleDateFormat sdf = new SimpleDateFormat(TIMEFORMAT_FULL); Date dateTime1 = sdf.parse(compTime1, new java.text.ParsePosition(0)); Date dateTime2 = sdf.parse(compTime2, new java.text.ParsePosition(0)); iReturn = dateTime2.getTime() / 1000L - dateTime1.getTime() / 1000L; return iReturn; } else { return 0; } } /** * Function name: lTimeCompareNow Description: 与当前时间比较. Compare one time * with now * * @param compTime1 比较时间1(格式:TimeFormat1) * @return long 返回相差的时间(单位:秒) */ public static long lTimeCompareNow(String compTime1) { if (compTime1 != null && compTime1.equals("999")) { return -1; } if (compTime1.length() == 19 || compTime1.length() == 10) { long iReturn = -1; if (compTime1.length() == 10) { compTime1 += " 00:00:00"; } SimpleDateFormat sdf = new SimpleDateFormat(TIMEFORMAT_FULL); Date dateTime1 = sdf.parse(compTime1, new java.text.ParsePosition(0)); iReturn = java.lang.System.currentTimeMillis() / 1000L - dateTime1.getTime() / 1000L; return iReturn; } else { return 0; } } /** * Function name: fmtDate Description: 日期字符串规范化. format a date string using * comm * * @param sDate 要规范的日期字符串(如2003-11-11、2003/11/11) * @param comm 日期字符串中间的分隔符 * @return String 返回规范化后的字符串 */ public static String fmtDate(String sDate, String comm) { String dRet = ""; if (sDate.length() == 10) { } else { sDate = getCurrentDate(); } dRet = sDate.substring(0, 4) + comm + sDate.substring(5, 7) + comm + sDate.substring(8, 10); return dRet; } /** * Function name: fmtDateTime Description: 日期时间字符串规范化. format a date string * using comm * * @param sDate 要规范的日期时间字符串(如2003-11-11 11:11:11、2003/11/11 11:11:11) * @param comm 日期中间的分隔符 * @return String 返回规范化后的字符串 */ public static String fmtDateTime(String sDate, String comm) { String dRet = ""; if (sDate.length() == 19) { } else { sDate = getCurrentDateTime(); } dRet = sDate.substring(0, 4) + comm + sDate.substring(5, 7) + comm + sDate.substring(8, 10) + " " + sDate.substring(11, 13) + ":" + sDate.substring(14, 16) + ":" + sDate.substring(17, 19); return dRet; } /** * Function Name: SubStr Description: 取指定长度的字符子串,超过取到串尾 * * @param fullString 源字符串 * @param nStart 开始字节 * @param nLen 要取的长度 * @return String 返回目的字符串 */ public static String subStr(String fullString, int nStart, int nLen) { String sResult = ""; if ((nStart + nLen) > fullString.length()) { sResult = fullString.substring(nStart); } else { sResult = fullString.substring(nStart, (nStart + nLen)); } return sResult; } /** * Function Name: DevideStr Description: 分解字符串 * * @param fullString 源字符串 * @param sComm 字符串中间的分隔符 * @return Vector 返回分解后的字符串列 */ public static Vector<String> devideStr(String fullString, String sComm) { Vector<String> vTmp = new Vector<String>(); try { if (sComm.length() > 1) { sComm = sComm.substring(0, 1); } StringTokenizer stString = new StringTokenizer(fullString, sComm); while (stString.hasMoreTokens()) { vTmp.addElement(stString.nextToken()); } } catch (Exception e) { vTmp.clear(); } return vTmp; } /** * Function Name: DivideCSV Description: 分解CSV格式字符串 * * @param fullString 源字符串 * @param sComm 字符串中间的分隔符 * @return Vector 返回分解后的字符串列 * @see #devideStr(String, String) deprecated 由DevideStr(String, * String)函数替代,该函数不再使用。 */ public static Vector<String> divideCSV(String fullString, String sComm) { Vector<String> vTmp = new Vector<String>(); if (sComm.length() > 1) { sComm = sComm.substring(0, 1); } StringTokenizer stString = new StringTokenizer(fullString, sComm); while (stString.hasMoreTokens()) { vTmp.addElement(stString.nextToken()); } return vTmp; } /** * Function Name: GenRandom Description: 随机数产生程序 * * @param nIn 随机数种子 * @param nLen 随机数长度 * @return String 返回随机数 */ public static String genRandom(int nIn, int nLen) { int nYear; int nMonth; int nDay; int nHour; int nSec; int nMsec; double f1; double f2; long temp; int count; int loopCount; int i; int rest; String sResult = ""; String sFull = ""; if (nLen > 9) { loopCount = nLen / 9; for (i = 1; i <= loopCount; i++) { sResult = sResult + genRandom(i, 9); } rest = nLen - loopCount * 9; if (rest != 0) { sResult = sResult + genRandom(1, rest); } } else { if (nLen == 0) { return ""; } sFull = ""; for (count = 1; count <= nLen; count++) { sFull = sFull + "0"; } DecimalFormat nf = new DecimalFormat(sFull); Calendar nowTime = Calendar.getInstance(); nYear = nowTime.get(Calendar.YEAR); nMonth = nowTime.get(Calendar.MONTH) + 1; nDay = nowTime.get(Calendar.DAY_OF_MONTH); nHour = nowTime.get(Calendar.HOUR_OF_DAY); nSec = nowTime.get(Calendar.SECOND); nMsec = nowTime.get(Calendar.MILLISECOND); f2 = Math.sin(Math.sqrt((nIn % 713) + nMsec + nSec * 34 + nHour * 47) + nMsec * nSec * nHour); f1 = Math.pow((Math.abs(f2 * 89 + 79 * Math.cos(nIn + nMsec * nSec)) * 31), 2); temp = (long) f1 + nIn + nYear + nMonth * 11 + nDay; StringBuffer stemp = new StringBuffer((new java.lang.Long(temp)).toString()); stemp = stemp.reverse(); Random rd = new Random(); rd.setSeed(java.lang.Long.parseLong(stemp.toString()) + (nIn % 3)); sResult = nf.format(rd.nextInt((int) (Math.pow(10, nLen) - 1))); } return sResult; } /** * Function Name: VarlenRnd Description: 取可变长随机数,长度范围由参数指定 * * @param minLen 最小长度 * @param maxLen 最大长度 * @return String 返回随机数 */ public static String varlenRnd(int minLen, int maxLen) { String sResult = ""; if (minLen < maxLen) { int nLen = java.lang.Integer.parseInt(genRandom(3, 1)) % (maxLen - minLen + 1) + minLen; sResult = genRandom(3, nLen); } else { sResult = genRandom(3, maxLen); } return sResult; } /** * BCD码左对齐转字符串 * * @param bcd 你一次读进的字节数,因为可能会大于你要处理的字节数 * @param begin 字节开始位置 * @param length 字节长,与begin一起决定真正要处理的字节数 * @return String 返回对齐后字符串 */ public static String bcd2Str(byte[] bcd, int begin, int length) { String str = ""; int temp; for (int i = begin; i < begin + length; i++) { if (bcd[i] == 0) { break; } temp = (bcd[i] & 0x0F) % 10; str += temp; temp = (bcd[i] >>> 4) % 10; if (bcd[i] >>> 4 != 0) { str += temp; } } return str; } /** * 普通的二进制转字串 * * @param hex 你一次读进的字节数,因为可能会大于你要处理的字节数 * @param begin 字节开始位置 * @param num 字节长,与begin一起决定真正要处理的字节数 * @return String 返回转换后字符串 */ public static String hex2Str(byte[] hex, int begin, int num) { String overflow = "overflow"; long ll = 0; if (num > 8) { return overflow; } for (int i = begin; i < begin + num; i++) { ll = ll * 256 + hex[i]; } return String.valueOf(ll); } /** * 获取日期的年份 * * @param d 日期 * @return 年份 */ public static int getYear(Date d) { GregorianCalendar cal = new GregorianCalendar(); if (d != null) { cal.setTime(d); return cal.get(Calendar.YEAR); } else { return 1900; } } /** * 获取日期的月份 * * @param d 日期 * @return 月份 */ public static int getMonth(Date d) { GregorianCalendar cal = new GregorianCalendar(); if (d != null) { cal.setTime(d); return cal.get(Calendar.MONTH) + 1; } else { return 1; } } /** * 获取日期的天 * * @param d 日期 * @return 天 */ public static int getDay(Date d) { GregorianCalendar cal = new GregorianCalendar(); if (d != null) { cal.setTime(d); return cal.get(Calendar.DAY_OF_MONTH); } else { return 1; } } /** * 获取日期的小时 * * @param d 日期 * @return 小时 */ public static int getHour(Date d) { GregorianCalendar cal = new GregorianCalendar(); if (d != null) { cal.setTime(d); return cal.get(Calendar.HOUR_OF_DAY); } else { return 0; } } /** * 获取日期的分 * * @param d 日期 * @return 分 */ public static int getMinute(Date d) { GregorianCalendar cal = new GregorianCalendar(); if (d != null) { cal.setTime(d); return cal.get(Calendar.MINUTE); } else { return 0; } } /** * 获取日期的秒 * * @param d 日期 * @return 秒 */ public static int getSecond(Date d) { GregorianCalendar cal = new GregorianCalendar(); if (d != null) { cal.setTime(d); return cal.get(Calendar.SECOND); } else { return 0; } } /** * 获取日期的毫秒 * * @param d 日期 * @return 毫秒 */ public static int getMilliSecond(Date d) { GregorianCalendar cal = new GregorianCalendar(); if (d != null) { cal.setTime(d); return cal.get(Calendar.MILLISECOND); } else { return 0; } } /** * 转换日期为MM-dd-yyyy HH:mm:ss格式的字符串 * * @param d 日期 * @return 字符串 */ public static String toString(Date d) { if (d == null) { return null; } return toString(d, DEFAULT_DATETIME_FORMAT); } /** * 转换日期为指定格式的字符串 * * @param date 日期 * @param format 指定格式 * @return 字符串 */ public static String toString(Date date, String format) { if (date == null) { return ""; } if ((format == null) || (format.length() == 0)) { return ""; } SimpleDateFormat formatter = new SimpleDateFormat(format); return formatter.format(date); } /** * 转换日期为指定区域内指定格式的字符串 * * @param date 日期 * @param format 指定格式 * @param locale 指定区域 * @return 字符串 */ public static String toString(Date date, String format, Locale locale) { if (date == null) { return ""; } if ((format == null) || (format.length() == 0)) { return ""; } if (locale == null) { return ""; } SimpleDateFormat formatter = new SimpleDateFormat(format, locale); return formatter.format(date); } /** * 转换字符串为日期 * * @param s 字符串 * @return 日期 */ public static Date toDate(String s) { if ((s == null) || (s.length() == 0)) { return null; } return toDate(s, DEFAULT_DATETIME_FORMAT); } /** * 转换字符串为指定格式的日期 * * @param s 字符串 * @param format 指定格式 * @return 日期 */ public static Date toDate(String s, String format) { if ((s == null) || (s.length() == 0)) { return null; } if ((format == null) || (format.length() == 0)) { return null; } SimpleDateFormat formatter = new SimpleDateFormat(format); ParsePosition pos = new ParsePosition(0); Date d = formatter.parse(s, pos); return d; } /** * 转换字符串为指定区域内指定格式的日期 * * @param s 字符串 * @param format 指定格式 * @param locale 指定区域 * @return 日期 */ public static Date toDate(String s, String format, Locale locale) { Locale loc; if ((s == null) || (s.length() == 0)) { return null; } if ((format == null) || (format.length() == 0)) { return null; } if (locale == null) { loc = Locale.getDefault(); } else { loc = locale; } SimpleDateFormat formatter = new SimpleDateFormat(format, loc); ParsePosition pos = new ParsePosition(0); Date d = formatter.parse(s, pos); return d; } /** * 判断字符串是否为日期 * @param s 字符串 * @return 是否为日期 */ public static boolean isDate(String s) { Date date = toDate(s); if (date == null) { return false; } String str = toString(date); return str.equalsIgnoreCase(s); } /** * 判断字符串是否为指定格式日期 * @param s 字符串 * @param format 指定格式 * @return 是否为日期 */ public static boolean isDate(String s, String format) { Date date = toDate(s, format); if (date == null) { return false; } String str = toString(date, format); return str.equalsIgnoreCase(s); } /** * 判断字符串是否为指定区域内指定格式日期 * @param s 字符串 * @param format 指定格式 * @param locale 指定区域 * @return 是否为日期 */ public static boolean isDate(String s, String format, Locale locale) { Date date = toDate(s, format, locale); if (date == null) { return false; } String str = toString(date, format, locale); return str.equalsIgnoreCase(s); } /** * 比较两日期是否相等 * @param d0 日期0 * @param d1 日期1 * @return 是否相等 */ public static boolean compare(Date d0, Date d1) { if (d0 == null && d1 == null) { return true; } if (d0 == null || d1 == null) { return false; } else { return d0.getTime() == d1.getTime(); } } /** * 将日期转换为YYYYMMDDHHMISS类型的方法 * * @param d Date * @return String */ public static String toDate(Date d) { return toString(d, ZH_SECOND_DATE_FORMAT); } /** * 将日期类型转换为微秒级别的字符串,格式为yyyy:MM:dd HH:mm:ss:SSS * * @param d Date * @return String */ public static String toDateOfMilliSecond(Date d) { return toString(d, DEFAULT_PRECISION_MILLTIME_FORMAT); } /** * 返回某日期增减指定月数后的新值 * * @param oldDate 旧日期,格式:yyyyMMddHHmmss * @param valve 增减月数 * @return 新日期,格式:yyyyMMddHHmmss */ public static String getDateByAddMonth(String oldDate, int valve) { Calendar calendar = Calendar.getInstance(); calendar.setTime(toDate(oldDate, ZH_SECOND_DATE_FORMAT)); calendar.add(Calendar.MONTH, valve); return DateUtil.toDate(calendar.getTime()); } /** * 计算增加年份后新的日期的值 * * @param oldDate 之前的日期,精确到秒级,字符串类型,如20060901235959 * @param valve 阀值 * @return 新日期 */ public static String getDateByAddYear(String oldDate, int valve) { int year = Integer.parseInt(oldDate.substring(0, 4)); String newDate = null; newDate = String.valueOf(year + valve) + oldDate.substring(4, oldDate.length()); return newDate; } /** * 计算增加日期后新的日期的值。 * * @param oldDate 之前的日期,精确到秒级,字符串类型,如20060901235959 * @param valve 阀值 * @return 新日期 */ public static String getDateByAddDay(String oldDate, int valve) { Date a = toDate(oldDate, ZH_SECOND_DATE_FORMAT); long b = a.getTime(); long c = b + valve * 24 * 60 * 60 * 1000; Date d = new Date(c); return toDate(d); } /** * 计算增加小时后新的日期的值。 * * @param oldDate 之前的日期,精确到秒级,字符串类型,如20060901235959 * @param valve 阀值 * @return 新日期 */ public static String getDateByAddHour(String oldDate, int valve) { Date a = toDate(oldDate, ZH_SECOND_DATE_FORMAT); long b = a.getTime(); long c = b + valve * 60 * 60 * 1000; Date d = new Date(c); return toDate(d); } /** * 计算增加分钟后新的日期的值。 * * @param oldDate 之前的日期,精确到秒级,字符串类型,如20060901235959 * @param valve 阀值 * @return 新日期 */ public static String getDateByAddMinute(String oldDate, int valve) { Date a = toDate(oldDate, ZH_SECOND_DATE_FORMAT); long b = a.getTime(); long c = b + valve * 60 * 1000; Date d = new Date(c); return toDate(d); } /** * 计算增加秒钟后新的日期的值。 * * @param oldDate 之前的日期,精确到秒级,字符串类型,如20060901235959 * @param valve 阀值 * @return 新日期 */ public static String getDateByAddSecond(String oldDate, int valve) { Date a = toDate(oldDate, ZH_SECOND_DATE_FORMAT); long b = a.getTime(); long c = b + valve * 1000; Date d = new Date(c); return toDate(d); } /** * 取得当前时间 falg=0 格式为:yyyy.MM.dd HH:mm:ss falg=1 格式为:mm * * @param flag 标志 * @return 当前时间 */ public static String getTime(int flag) { java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); String operTime = formatter.format(new java.util.Date()); String sMoth = operTime.substring(5, 7); if (flag == 0) { return operTime; } else { return sMoth; } } /** * 判断是否是闰年 * @param year 年份 * @return 是否是闰年 */ public static boolean isLeapYear(int year) { if (year < 0) { return false; } if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { return true; } else { return false; } } /** * 把传进来的 日期+时间 格式填充。把时间的 时、分、秒的数字填充为2位。不足2位的前面补0 * * @param datetime 日期 * @return 补充后的日期 */ public static String fillDateTime(String datetime) { if (datetime == null || datetime.trim().length() == 0) { return ""; } String[] ary = datetime.split(" "); if (ary == null || ary.length != 2) { //这里对日期时间不做合法性检查。设定该日期时间都是合法的。 //简单的检查下,如果格式不合法,直接返回空字符串 return ""; } //这里暂时对日期格式不做转换,只对时间格式做转换 String time = fillTime(ary[1]); if (time.trim().length() == 0) {//如果时间格式转换错误,则返回空字符串 return ""; } String date = fillDate(ary[0].replaceAll("\\.", "-")); if (date.trim().length() == 0) { return ""; } return date + " " + time; } /** * 填充日期 * @param date 日期 * @return 日期 */ public static String fillDate(String date) { if (date == null || date.length() == 0) { return ""; }//2009-9-9 String[] ary = date.split("-"); if (ary.length != 3 || ary[1] == null || ary[1].trim().length() == 0 || ary[2] == null || ary[2].trim().length() == 0 || (ary[1].trim().length() != 1 && ary[1].trim().length() != 2) || (ary[2].trim().length() != 1 && ary[2].trim().length() != 2)) { return ""; } if (ary[1].length() == 1) { ary[1] = "0" + ary[1]; } if (ary[2].length() == 1) { ary[2] = "0" + ary[2]; } return ary[0] + "-" + ary[1] + "-" + ary[2]; } /** * 填充时间格式. 把时间的 时、分、秒的数字填充为2位。不足2位的前面补0 转换后的格式为: HH:mm:ss * * @param time 日期 * @return 日期 */ public static String fillTime(String time) { //这里对时间的合法性不做检查 if (time == null) { return ""; } time = time.trim(); if (time.equals("")) { return ""; } String[] timesplit = time.split(":", 3); if (timesplit.length != 3) { return ""; } if (timesplit[0] == null || timesplit[1] == null || timesplit[2] == null) { return ""; } String shour = timesplit[0].trim(); String sminute = timesplit[1].trim(); String ssecond = timesplit[2].trim(); if (shour.equals("") || sminute.equals("") || ssecond.equals("")) { return ""; } if (shour.length() == 1) { shour = "0" + shour; } if (sminute.length() == 1) { sminute = "0" + sminute; } if (ssecond.length() == 1) { ssecond = "0" + ssecond; } return shour + ":" + sminute + ":" + ssecond; } /** * 检测输入字符串是否是时间格式 HH:mm:dd * * @param s 日期 * @return 是否是时间格式 */ public static boolean checkTimeFormat(String s) { if (s == null) { return false; } s = s.trim(); if (s.equals("")) { return false; } String[] timesplit = s.split(":", 3); if (timesplit.length != 3) { return false; } if (timesplit[0] == null || timesplit[1] == null || timesplit[2] == null) { return false; } String shour = timesplit[0].trim(); String sminute = timesplit[1].trim(); String ssecond = timesplit[2].trim(); if (shour.equals("") || sminute.equals("") || ssecond.equals("")) { return false; } try { int ihour = Integer.parseInt(shour); if (shour.trim().length() != 2 && shour.trim().length() != 1) { return false; } if (ihour > 23 || ihour < 0) { return false; } if (sminute.trim().length() != 2 && sminute.trim().length() != 1) { return false; } int iminute = Integer.parseInt(sminute); if (iminute < 0 || iminute > 59) { return false; } if (ssecond.trim().length() != 2 && ssecond.trim().length() != 1) { return false; } int isecond = Integer.parseInt(ssecond); if (isecond < 0 || isecond > 59) { return false; } } catch (Exception e) { return false; } return true; } /** * 检测输入字符串是否是 日期+时间 格式,包括闰年检测 * @param s 日期 * @return 是否是日期+时间 格式 */ public boolean checkDateTimeFormat(String s) { if (s == null) { return false; } s = s.trim(); if (s.equals("")) { return false; } String[] dtparts = s.split(" ", 2); if (dtparts.length != 2) { return false; } String dateparts = dtparts[0]; String timeparts = dtparts[1]; return checkDateFormat(dateparts) && checkTimeFormat(timeparts); } /** * 检测输入字符串是否是日期格式yyyy-MM-dd,包括闰年检测 * @param s 日期 * @return 是否是日期格式yyyy-MM-dd */ public static boolean checkDateFormat(String s) { if (s == null) { return false; } s = s.trim(); if (s.equals("")) { return false; } String[] dts = s.split("-"); if (dts.length != 3) { return false; } if (dts[0].length() != 4) { return false; } if ((dts[1].length() != 1 && dts[1].length() != 2)) { return false; } if (dts[2].length() != 1 && dts[2].length() != 2) { return false; } int year = 0; int month = 0; int day = 0; int days = 0; try { year = Integer.valueOf(dts[0]); if (year > 10000 || year < 1) { return false; } } catch (Exception e) { return false; } try { month = Integer.valueOf(dts[1]); if (month < 1 || month > 12) { return false; } } catch (Exception e) { return false; } try { day = Integer.valueOf(dts[2]); switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = 31; break; case 4: case 6: case 9: case 11: days = 30; break; case 2: if (isLeapYear(year)) { days = 29; } else { days = 28; } default: } if (day > days || day < 1) { return false; } } catch (Exception e) { return false; } return true; } /** * 把字符串转换成 日期 * @param strdate 字符串日期 * @return 日期 */ public Date stringParsetoDate(String strdate) { if (strdate == null || strdate.trim().equals("")) { return null; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { return sdf.parse(strdate); } catch (Exception e) { return null; } } /** * 把字符串转换成 日期时间 * @param str 字符串日期 * @return 日期 */ public Date strToDateTime(String str) { if (str == null || str.trim().equals("")) { return null; } java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { return sdf.parse(str); } catch (Exception e) { return null; } } /** * 从字符串中得到月份 * @param datestr 字符串日期 * @return 月份 */ public int getMonthfromStr(String datestr) { int month = 0; if (datestr == null || datestr.trim().equals("")) { return month; } String[] splitedate = datestr.split("-"); try { month = Integer.parseInt(splitedate[1].trim()); if (month < 1 || month > 12) { return 0; } } catch (Exception e) { e.printStackTrace(); return 0; } return month; } /** * 把给定日期减去N个月,返回一个Date * @param date 给定日期 * @param nMonth 月数 * @return Date * @throws Exception 抛出的异常 */ public Date minusMonth(Calendar date, int nMonth) throws Exception { date.add(Calendar.MONTH, -nMonth); SimpleDateFormat spdf = new SimpleDateFormat("yyyy-MM-dd"); return spdf.parse(spdf.format(date.getTime())); } }
时间: 2024-10-02 07:56:54