java 日期时间操作

/**
  * 从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;
  }
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值