项目中时间格式字符转换成日期

上一个项目做完了闲置了一段时间所以有一些时间将项目中一些小经验整理分享一下,也防止下次使用的时候找不到。

第一次完整的负责一个项目的框架搭建技术选型,所以也注意到了之前所忽略的一些小问题,这次拿出一个点单独分析。

访问时使用get方法直接在地址栏中输入参数看看会出现什么问题

没有任何操作的话时间格式的字符还时字符串并不能直接赋值给时间类型的变量。

@InitBinder
public void initBinder(WebDataBinder binder) {
   binder.registerCustomEditor(String.class, null, new StringTrimmerEditor("", false));
   binder.registerCustomEditor(Date.class, new DateConverter());
}

创建DateConverter

public class DateConverter extends PropertyEditorSupport {

   private static final List<String> formarts = new ArrayList<String>(4);

   static {
      formarts.add("yyyy-MM");
      formarts.add("yyyy-MM-dd");
      formarts.add("yyyy-MM-dd HH:mm");
      formarts.add("yyyy-MM-dd HH:mm:ss");
   }

   public Date convert(String source) {
      String value = source.trim();
      if ("".equals(value)) {
         return null;
      }
      if (source.matches("^\\d{4}-\\d{1,2}$")) {
         return parseDate(source, formarts.get(0));
      } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
         return parseDate(source, formarts.get(1));
      } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) {
         return parseDate(source, formarts.get(2));
      } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
         return parseDate(source, formarts.get(3));
      } else {
         return null;
      }
   }

   /**
    * 功能描述:格式化日期
    *
    * @param dateStr
    *            String 字符型日期
    * @param format
    *            String 格式
    * @return Date 日期
    */
   public Date parseDate(String dateStr, String format) {
      Date date = null;
      try {
         DateFormat dateFormat = new SimpleDateFormat(format);
         date = (Date) dateFormat.parse(dateStr);
      } catch (Exception e) {
      }
      return date;
   }

   public void setAsText(String text) throws IllegalArgumentException {
      Date date = convert(text);
      setValue(date);
   }

}

已经可以实现日期格式字符转换成时间格式如果有特殊格式可以更改DateConverter中的静态代码块的内容

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值