各种类型转为Date

最近遇到个问题,就是Java的Excel导入时,对Excel中的日期做处理,常规模式用下面这种方法处理

HSSFCell birthDateCell = row.getCell(col++);

Date date = birthDateCell.getDateCellValue(); 

今天推荐下面这种做法:

首先定一个方法,做返回date类型,需要传object值类型

  public  static Date getDate(Object o)
  {
     if (o ==  null)
       return  null;
     if (o  instanceof Date)
       return ((Date)o);
     if (o  instanceof String)
       return getDate(String.valueOf(o));
     if (o  instanceof Timestamp)
       return  new Date(((Timestamp)o).getTime());
     if (o  instanceof Date)
       return  new Date(((Date)o).getTime());

     return  null;  

  } 

或者这样

 public static Date getDate(String dateStr)

  {
    Date temp1 =  null;
     if (dateStr ==  null)
       return  null;
     if (dateStr.equals(""))
       return  null;
    SimpleDateFormat formatter =  null;
     try {
       if (dateStr.indexOf(" ") != -1) {
        String[] aa = StringUtils.split(dateStr, ":");
         if (aa.length == 3)
          formatter =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         else  if (aa.length == 2)
          formatter =  new SimpleDateFormat("yyyy-MM-dd HH:mm");
         else
          formatter =  new SimpleDateFormat("yyyy-MM-dd HH");

      }
       else  if (dateStr.indexOf("-") == -1) {
        formatter =  new SimpleDateFormat("yyyyMMdd");
      }  else {
        formatter =  new SimpleDateFormat("yyyy-MM-dd");
      }

      temp1 = formatter.parse(dateStr);
    }  catch (Exception e) {
      e.printStackTrace();
    }
     return temp1;
  }

然后做Java的Excel导入时,就可以操作时间了

 HSSFCell registerTimeCell = row.getCell(col++);

 Date date = DateUtil.getDate(getCellValue(registerTimeCell));

把上面的2个 getDate方法放到你定义的类里面去,方便使用

转载于:https://www.cnblogs.com/nxblog/p/4615500.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值