java 日期时间操作

来源:互联网 发布:淘宝食品网 编辑:程序博客网 时间:2024/05/01 20:13

/**
  * 从yyyy-MM-dd HH:mm:ss类型的字符串 获取Date类型的日期
  *
  * @param text
  *            日期文本格式
  * @return Date 日期信息
  */
 public static Date getDate(String text) {
  if(isEmpty(text)) {return null;};
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  Date date = new Date();
  try {
   date = sdf.parse(text);
  } catch (ParseException e) {
   e.printStackTrace();
  }
  return date;
 }
 
 /**
  *  Java 判断字符串是否为空的方法.
  * @param s
  * @return
  */
 public static boolean isEmpty(String s) {
  return (s == null || s.length() <= 0);
 }
 
 /**
  * 将日期型的字符串,转换成日期型 在此基础上添加n天数
  * @param strDate
  * @param n
  * @return
  */
 public static String getAddDate(String strDate,int n) {
  if(!isEmpty(strDate)) {
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
   Calendar cal = Calendar.getInstance();
   Date end_date=null;
   try {
    end_date=sdf.parse(strDate);
    cal.setTime(end_date);
    cal.add(Calendar.DATE, n);
    return sdf.format(cal.getTime());
   } catch (ParseException e) {
    e.printStackTrace();
    return null;
   }
  }
  return null;
 }

 

 

/**
  * 计算两个时间间隔的秒数
  * @param strStartDate
  * @param strEndDate
  * @return
  */
 public static long getDiscrepancyTime(String strStartDate,String strEndDate) {
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
  Calendar cal = Calendar.getInstance();
  Calendar calE= Calendar.getInstance();
  Date date_start;
  Date date_end;
  long diffMins = 1;
  try {
   date_start = sdf.parse(strStartDate);
   cal.setTime(date_start);
   date_end=sdf.parse(strEndDate);
   calE.setTime(date_end);
   if(cal.before(calE)) {
    //两个日期相差的秒  
    return (calE.getTimeInMillis()-cal.getTimeInMillis())/1000;
   }
   return diffMins;
  } catch (ParseException e) {
   e.printStackTrace();
   return 1;
  }
 }