jimingminlovefly

统计

最新评论

案例-自定义的工具类DateUtil 和StringUtil

package com.lvyou.util;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.log4j.Logger;


public class DateUtil {
 final static Logger logger = Logger.getLogger(DateUtil.class);
 
 private final static String[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", };

 public final static Date parseComplicateDate(String str) {
  try{
   if (StringUtil.isNullOrEmpty(str))
    return null;
   String[] strs = str.split(" ");
   int nYear = Integer.parseInt(strs[5]);
   int nMonth = 0;
   for (int i = 0; i < months.length; i++) {
    if (months[i].equals(strs[1])) {
     nMonth = i;
     break;
    }
   }
   int nDay = Integer.parseInt(strs[2]);
   String strTime = strs[3];
   String[] strTimes = strTime.split(":");
   int nHour = Integer.parseInt(strTimes[0]);
   int nMinute = Integer.parseInt(strTimes[1]);
   int nSecond = Integer.parseInt(strTimes[2]);
   Calendar cal = new GregorianCalendar(nYear, nMonth, nDay, nHour,
     nMinute, nSecond);
   Date aDate = cal.getTime();
   return aDate;
  }
  catch (ArrayIndexOutOfBoundsException e){
   logger.warn("", e);
   return null;
  }
  catch (NumberFormatException e){
   logger.warn("", e);
   return null;
  }
  catch (Exception e){
   logger.warn("", e);
   return null;
  }
 }

 /**
  * 返回用户指定日期的前或后n天的字符串 正数为向后n天,负数相反
  * @param date
  * @param day
  * @return
  * @throws ParseException
  */
 public static String  getNumToDate(String date,int day) throws ParseException
 {
  
  Calendar c = Calendar.getInstance();

  SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
  c.setTime(sdf1.parse(date));
  c.add( Calendar.DAY_OF_MONTH, day );
  
  return sdf1.format(c.getTime());
 }
 
 public final static Date getYyyyMmDdHhMmss(String str) {
  if (StringUtil.isNullOrEmpty(str))
   return null;
  try{
   String[] strs = str.split(" ");
   String[] strDays = strs[0].split("-");
   int nYear = Integer.parseInt(strDays[0]);
   int nMonth = Integer.parseInt(strDays[1]);
   int nDay = Integer.parseInt(strDays[2]);

   String[] strTimes = strs[1].split(":");
   int nHour = Integer.parseInt(strTimes[0]);
   int nMinute = Integer.parseInt(strTimes[1]);
   int nSecond = Integer.parseInt(strTimes[2]);
   Calendar cal = new GregorianCalendar(nYear, nMonth-1, nDay, nHour,
     nMinute, nSecond);
   return cal.getTime();
  }
  catch (ArrayIndexOutOfBoundsException e){
   logger.warn("", e);
   return null;
  }
  catch (NumberFormatException e){
   logger.warn("", e);
   return null;
  }
  catch (Exception e){
   logger.warn("", e);
   return null;

  }
 }
 
 /**
  * 返回与指定日期n个月的日期
  * @param date
  * @param day
  * @return
  * @throws ParseException
  */
 public static Date  getMonthToDate(Date date,int month) throws ParseException
 {
  Calendar c = Calendar.getInstance();
  c.setTime(date);
        c.add(Calendar.DAY_OF_MONTH, -month*30);
        return c.getTime();
 }
 
 /**
  * 返回用户指定日期的前或后n天的字符串 正数为向后n天,负数相反
  * @param date
  * @param day
  * @return
  * @throws ParseException
  */
 public static Date  getNumToDate(Date date,int day) throws ParseException
 {
  Calendar c = Calendar.getInstance();
  c.add( Calendar.DAY_OF_MONTH, day );
  return c.getTime();
 }
 
 /**
  * 比较两个日期
  * @param date1
  * @param date2
  * @return
  */
 public static boolean compareDate(Date date1,Date date2)
 {
  Calendar c = Calendar.getInstance();
  c.setTime(date1);
  c.add( Calendar.DAY_OF_MONTH, 1 );
  return  c.getTime().getTime()>date2.getTime()?true:false;
 }
 
 
 
 
 
 
 
 
 public static void main(String[] args) throws ParseException {
  SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
  
  System.out.println(autoCommit());
 }
 
 public final static Date getYyyyMmDdHhMm(String str) {
  if (StringUtil.isNullOrEmpty(str))
   return null;
  try{
   String[] strs = str.split(" ");
   String[] strDays = strs[0].split("-");
   int nYear = Integer.parseInt(strDays[0]);
   int nMonth = Integer.parseInt(strDays[1]);
   int nDay = Integer.parseInt(strDays[2]);

   String[] strTimes = strs[1].split(":");
   int nHour = Integer.parseInt(strTimes[0]);
   int nMinute = Integer.parseInt(strTimes[1]);
   int nSecond = 0;
   Calendar cal = new GregorianCalendar(nYear, nMonth-1, nDay, nHour,
     nMinute, nSecond);
   return cal.getTime();
  }
  catch (ArrayIndexOutOfBoundsException e){
   logger.warn("", e);
   return null;
  }
  catch (NumberFormatException e){
   logger.warn("", e);
   return null;
  }
  catch (Exception e){
   logger.warn("", e);
   return null;

  }
 }
 public final static Date getYyyyMmDdHhMmSsFlexible(String str) {
  if (StringUtil.isNullOrEmpty(str))
   return null;
  try{
   String[] strs = str.split(" ");
   String[] strDays = strs[0].split("-");
   int nYear = Integer.parseInt(strDays[0]);
   int nMonth = Integer.parseInt(strDays[1]);
   int nDay = Integer.parseInt(strDays[2]);

   int nHour = 0;
   int nMinute = 0;
   int nSecond = 0;
   if (strs.length > 1){
    String[] strTimes = strs[1].split(":");
    if (strTimes.length > 1)
     nHour = Integer.parseInt(strTimes[0]);
    if (strTimes.length > 2)
     nMinute = Integer.parseInt(strTimes[1]);
    if (strTimes.length > 3)
     nSecond = Integer.parseInt(strTimes[2]);
   }
   Calendar cal = new GregorianCalendar(nYear, nMonth-1, nDay, nHour,
     nMinute, nSecond);
   return cal.getTime();
  }
  catch (ArrayIndexOutOfBoundsException e){
   logger.warn("", e);
   return null;
  }
  catch (NumberFormatException e){
   logger.warn("", e);
   return null;
  }
  catch (Exception e){
   logger.warn("", e);
   return null;

  }
 }
 public final static Date getHhMm(String str) {
  if (StringUtil.isNullOrEmpty(str))
   return null;
  try{
   String[] strTimes = str.split(":");
   int nHour = Integer.parseInt(strTimes[0]);
   int nMinute = Integer.parseInt(strTimes[1]);
   int nSecond = 0;
   Calendar cal = new GregorianCalendar(nHour,
     nMinute, nSecond);
   return cal.getTime();
  }
  catch (ArrayIndexOutOfBoundsException e){
   logger.warn("", e);
   return null;
  }
  catch (NumberFormatException e){
   logger.warn("", e);
   return null;
  }
  catch (Exception e){
   logger.warn("", e);
   return null;

  }
 }
 public final static Date getYyyyMmDd(String str) {
  if (StringUtil.isNullOrEmpty(str))
   return null;
  try{
//   String[] strs = str.split(" ");
   String[] strDays = str.split("-");
   int nYear = Integer.parseInt(strDays[0]);
   int nMonth = Integer.parseInt(strDays[1]);
   int nDay = Integer.parseInt(strDays[2]);

   Calendar cal = new GregorianCalendar(nYear, nMonth-1, nDay, 0,
     0, 0);
   return cal.getTime();
  }
  catch (ArrayIndexOutOfBoundsException e){
   logger.warn("", e);
   return null;
  }
  catch (NumberFormatException e){
   logger.warn("", e);
   return null;
  }
  catch (Exception e){
   logger.warn("", e);
   return null;
  }
 }
 
 public final static Date getYyyyMmDdNotHyphenated(String str) {
  if (StringUtil.isNullOrEmpty(str))
   return null;
  try{
//   String[] strs = str.split(" ");
   int nYear = Integer.parseInt(str.substring(0, 4));
   int nMonth = Integer.parseInt(str.substring(4, 6));
   int nDay = Integer.parseInt(str.substring(6, 8));

   Calendar cal = new GregorianCalendar(nYear, nMonth-1, nDay, 0,
     0, 0);
   return cal.getTime();
  }
  catch (ArrayIndexOutOfBoundsException e){
   logger.warn("", e);
   return null;
  }
  catch (NumberFormatException e){
   logger.warn("", e);
   return null;
  }
  catch (Exception e){
   logger.warn("", e);
   return null;
  }
 }
 
 public final static Date getYyMmDd(String str) {
  if (StringUtil.isNullOrEmpty(str))
   return null;
  try{
//   String[] strs = str.split(" ");
   String[] strDays = str.split("-");
   int nYear = Integer.parseInt(strDays[0]);
   nYear += 2000;
   int nMonth = Integer.parseInt(strDays[1]);
   int nDay = Integer.parseInt(strDays[2]);

   Calendar cal = new GregorianCalendar(nYear, nMonth-1, nDay, 0,
     0, 0);
   return cal.getTime();
  }
  catch (ArrayIndexOutOfBoundsException e){
   logger.warn("", e);
   return null;
  }
  catch (NumberFormatException e){
   logger.warn("", e);
   return null;
  }
  catch (Exception e){
   logger.warn("", e);
   return null;
  }
 }
 
 public final static Date getYyMmDdNotHyphenated(String str) {
  if (StringUtil.isNullOrEmpty(str))
   return null;
  try{
   int nYear = Integer.parseInt(str.substring(0,2));
   nYear += 2000;
   int nMonth = Integer.parseInt(str.substring(2,4));
   int nDay = Integer.parseInt(str.substring(4,6));

   Calendar cal = new GregorianCalendar(nYear, nMonth-1, nDay, 0,
     0, 0);
   return cal.getTime();
  }
  catch (ArrayIndexOutOfBoundsException e){
   logger.warn("", e);
   return null;
  }
  catch (NumberFormatException e){
   logger.warn("", e);
   return null;
  }
  catch (Exception e){
   logger.warn("", e);
   return null;
  }
 }
 
 public final static String toYyMmdd(Date aDate){
  if (aDate == null)
   return "";
  Calendar cal = new GregorianCalendar();
  cal.setTime(aDate);
  StringBuilder sb = new StringBuilder();
  int nYear = cal.get(Calendar.YEAR);
  nYear = nYear % 100;
  int nMonth = cal.get(Calendar.MONTH);
  nMonth++;
  int nDay = cal.get(Calendar.DAY_OF_MONTH);
  if (nYear < 10)
   sb.append('0');
  sb.append(nYear);
  if (nMonth < 10)
   sb.append('0');
  sb.append(nMonth);
  if (nDay < 10)
   sb.append('0');
  sb.append(nDay);
  return sb.toString();
 }
 public final static String toHyphenatedYyMmdd(Date aDate){
  if (aDate == null)
   return "";
  Calendar cal = new GregorianCalendar();
  cal.setTime(aDate);
  StringBuilder sb = new StringBuilder();
  int nYear = cal.get(Calendar.YEAR);
  nYear = nYear % 100;
  int nMonth = cal.get(Calendar.MONTH);
  nMonth++;
  int nDay = cal.get(Calendar.DAY_OF_MONTH);
  if (nYear < 10)
   sb.append('0');
  sb.append(nYear);
  sb.append('-');
  if (nMonth < 10)
   sb.append('0');
  sb.append(nMonth);
  sb.append('-');
  if (nDay < 10)
   sb.append('0');
  sb.append(nDay);
  return sb.toString();
 }
 public final static String toYyyyMmdd(Date aDate){
  if (aDate == null)
   return "";
  Calendar cal = new GregorianCalendar();
  cal.setTime(aDate);
  StringBuilder sb = new StringBuilder();
  int nYear = cal.get(Calendar.YEAR);
  int nMonth = cal.get(Calendar.MONTH);
  nMonth++;
  int nDay = cal.get(Calendar.DAY_OF_MONTH);

  sb.append(nYear);
  if (nMonth < 10)
   sb.append('0');
  sb.append(nMonth);
  if (nDay < 10)
   sb.append('0');
  sb.append(nDay);
  return sb.toString();
 }
 public final static String toHyphenatedYyyyMmdd(Date aDate){
  if (aDate == null)
   return "";
  Calendar cal = new GregorianCalendar();
  cal.setTime(aDate);
  int nYear = cal.get(Calendar.YEAR);
  int nMonth = cal.get(Calendar.MONTH);
  nMonth++;
  int nDay = cal.get(Calendar.DAY_OF_MONTH);

  StringBuilder sb = new StringBuilder();
  sb.append(nYear);
  sb.append('-');
  if (nMonth < 10)
   sb.append('0');
  sb.append(nMonth);
  sb.append('-');
  if (nDay < 10)
   sb.append('0');
  sb.append(nDay);
  return sb.toString();
 }
 public final static String toHyphenatedYyyyMmDdHhMm(Date aDate){
  if (aDate == null)
   return "";
  Calendar cal = new GregorianCalendar();
  cal.setTime(aDate);
  int nYear = cal.get(Calendar.YEAR);
  int nMonth = cal.get(Calendar.MONTH);
  nMonth++;
  int nDay = cal.get(Calendar.DAY_OF_MONTH);
  int nHour = cal.get(Calendar.HOUR_OF_DAY);
  int nMinute = cal.get(Calendar.MINUTE);

  StringBuilder sb = new StringBuilder();
  sb.append(nYear);
  sb.append('-');
  if (nMonth < 10)
   sb.append('0');
  sb.append(nMonth);
  sb.append('-');
  if (nDay < 10)
   sb.append('0');
  sb.append(nDay);

  sb.append(" ");
  if (nHour < 10)
   sb.append('0');
  sb.append(nHour);
  
  sb.append(":");
  if (nMinute < 10)
   sb.append('0');
  sb.append(nMinute);

  return sb.toString();
 }
 public final static String toHyphenatedYyyyMmDdHhMmSsFlexible(Date aDate){
  if (aDate == null)
   return "";
  Calendar cal = new GregorianCalendar();
  cal.setTime(aDate);
  int nYear = cal.get(Calendar.YEAR);
  int nMonth = cal.get(Calendar.MONTH);
  nMonth++;
  int nDay = cal.get(Calendar.DAY_OF_MONTH);
  int nHour = cal.get(Calendar.HOUR_OF_DAY);
  int nMinute = cal.get(Calendar.MINUTE);
  int nSecond = cal.get(Calendar.SECOND);

  StringBuilder sb = new StringBuilder();
  sb.append(nYear);
  sb.append('-');
  if (nMonth < 10)
   sb.append('0');
  sb.append(nMonth);
  sb.append('-');
  if (nDay < 10)
   sb.append('0');
  sb.append(nDay);

  if (nHour > 0 ||
    nMinute > 0 ||
    nSecond > 0){
   
   sb.append(" ");
   if (nHour < 10)
    sb.append('0');
   sb.append(nHour);

   sb.append(":");
   if (nMinute < 10)
    sb.append('0');
   sb.append(nMinute);

   if (nSecond > 0){
    sb.append(":");
    if (nSecond < 10)
     sb.append('0');
    sb.append(nSecond);
   }
  }

  return sb.toString();
 }

 public final static String toYyyyMmddHHmm(Date aDate){
  if (aDate== null)
   return "";
  Calendar cal = new GregorianCalendar();
  cal.setTime(aDate);

  int nYear = cal.get(Calendar.YEAR);
  int nMonth = cal.get(Calendar.MONTH);
  nMonth++;
  int nDay = cal.get(Calendar.DAY_OF_MONTH);
  int nHour = cal.get(Calendar.HOUR_OF_DAY);
  int nMinute = cal.get(Calendar.MINUTE);
  
  StringBuilder sb = new StringBuilder();
  sb.append(nYear);
  sb.append("-");
  
  if (nMonth < 10)
   sb.append('0');
  sb.append(nMonth);
  sb.append("-");

  if (nDay < 10)
   sb.append('0');
  sb.append(nDay);
  sb.append(" ");

  if (nHour < 10)
   sb.append('0');
  sb.append(nHour);
  sb.append(":");
  
  if (nMinute < 10)
   sb.append('0');
  sb.append(nMinute);
  return sb.toString();
 }
 
 public final static String toYyyymmddHhmmss(Date aDate){
  if (aDate == null)
   return "";
  Calendar cal = new GregorianCalendar();
  cal.setTime(aDate);
  int nYear = cal.get(Calendar.YEAR);
  int nMonth = cal.get(Calendar.MONTH);
  nMonth++;
  int nDay = cal.get(Calendar.DAY_OF_MONTH);
  int nHour = cal.get(Calendar.HOUR_OF_DAY);
  int nMInute = cal.get(Calendar.MINUTE);
  int nSeconf= cal.get(Calendar.SECOND);

  StringBuilder sb = new StringBuilder();
  sb.append(nYear);
  sb.append('-');
  if (nMonth < 10)
   sb.append('0');
  sb.append(nMonth);
  sb.append('-');
  if (nDay < 10)
   sb.append('0');
  sb.append(nDay);

  sb.append(' ');
  
  if (nHour < 10)
   sb.append('0');
  sb.append(nHour);
  sb.append(':');
  if (nMInute < 10)
   sb.append('0');
  sb.append(nMInute);
  sb.append(':');
  if (nSeconf < 10)
   sb.append('0');
  sb.append(nSeconf);
  
  return sb.toString();
 }
 
 public final static String toHHmm(Date aDate){
  if (aDate== null)
   return "";
  Calendar cal = new GregorianCalendar();
  cal.setTime(aDate);

  int nHour = cal.get(Calendar.HOUR_OF_DAY);
  int nMinute = cal.get(Calendar.MINUTE);
  
  StringBuilder sb = new StringBuilder();
  

  if (nHour < 10)
   sb.append('0');
  sb.append(nHour);
  sb.append(":");
  
  if (nMinute < 10)
   sb.append('0');
  sb.append(nMinute);
  return sb.toString();
 }
 public static java.sql.Timestamp toTimestamp (Date theDate){
  if (theDate== null)
   return null;
  return new Timestamp (theDate.getTime());
 }
 
 /**
  * 判断当前的时小数是否在23:00---08:00内,如果在就自动commit到供应商下单
  * @return
  */
 public static boolean autoCommit(){
    SimpleDateFormat sdf=new SimpleDateFormat("HH");
       Date d=new Date();
       String str=sdf.format(d);
       int num=Integer.parseInt(str) ;
        return (num>=23 || num<8)?true:false;
 }
}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

package com.lvyou.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

public class StringUtil {
 static Logger logger = Logger.getLogger (StringUtil.class);
 public final static String ENCODING = "GBK";
  private static String[] strArray = new String[] { "a", "b", "c", "d", "e", 
         "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", 
         "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", 
        "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", 
         "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", 
         "5", "6", "7", "8", "9", "!", "@", "#", "$", "%", "^", "&", "(", 
         ")" };
 
 public static boolean isNullOrEmpty (String str){
  if (str== null ||
    "".equals(str))
   return true;
  else
   return false;
  
 }
 public static String nullToEmpty(String str){
  if (str== null)
   return "";
   return str;
  
 }
 public static String getEscaped(String str ){
  try {
   return URLEncoder.encode(str, ENCODING);
  } catch (UnsupportedEncodingException e) {
   logger.warn("", e);
  }
  return "";
 }
 
 /**
  * 校验手机号码
  * @param num
  * @return
  *
  */
 public static boolean IsMobileCode(String code)
 {
  String Code = "[0-9]{3}";
  if(isNumeric(code,Code))
   return true;
  else
   return false;
 }
 public static boolean IsMobileNum1(String num){
   String HK="[0-9]{8}";
   String MainLand="[0-9]{11}";
//   String USA="";
  if( (isNumeric(num,HK)==true || isNumeric(num,MainLand)==true ) && num.matches("^(13|15|18)\\d{9}$"))
   return true;
  else
   return false;
 }
 
 public static boolean IsMoblieNum(String num)
 {
   String Code="[0-9]{1,4}";
   String HK="[0-9]{8}";
   String MainLand="[0-9]{11}";
  if(num.trim()!=null || num.trim()!="")
  {
   String[] str=num.split(" ");
   if(isNumeric(str[0],Code))
   {
    if((isNumeric(str[1],HK)==true || isNumeric(str[1],MainLand)==true) && str[1].matches("^(13|15|18)\\d{6,9}$"))
    {
     
    return true;
    }
    else
    {
     return false;
    }
   }
   else
   {
    return false;
   }
  }
  else
  {
   return false;
  }
 }

 public static  boolean isNumeric(String str,String where )
 {
  Pattern pattern = Pattern.compile(where);
  Matcher isNum = pattern.matcher(str);
   if( !isNum.matches() )
   {
   return false;
   }
  return true;
 }
  
  /**
  * 生成唯一字符串 
  * @param length 需要长度
  * @param symbol 是否允许出现特殊字符 -- !@ $%^&*()
  * @return
  */ 
  public static String getUniqueString(int length, boolean symbol) 
        throws Exception { 
    Random ran = new Random(); 
    int num = ran.nextInt(61); 
    String returnString = ""; 
    String str = ""; 
    for (int i = 0; i < length;) { 
        if (symbol) 
            num = ran.nextInt(70); 
        else 
            num = ran.nextInt(61); 
        str = strArray[num]; 
        if (!(returnString.indexOf(str) >= 0)) { 
            returnString += str; 
            i++; 
        } 
    } 
    return returnString; 
  } 
 
  public static void main(String[] args) {

   System.out.println(IsMoblieNum("568 ga1345")?"对的":"错的");
//   
//   String str="16020895785";
//     System.out.println(str.matches("^(13|15|18)\\d{9}$"));

  }
}



posted on 2011-11-25 14:31 计明敏 阅读(745) 评论(0)  编辑  收藏 所属分类: java


只有注册用户登录后才能发表评论。


网站导航: