1. 程式人生 > >beanUtils之日期轉換器的使用

beanUtils之日期轉換器的使用

*@Test
	public void test2() throws Exception {
		// 模擬表單資料
		String name = "jack";
		String age = "20";
		String birth = "2015-12-12";
		
		// 物件
		Admin admin = new Admin();
		
		// 註冊日期型別轉換器:1, 自定義的方式
		ConvertUtils.register(new Converter() {
			// 轉換的內部實現方法,需要重寫
			@Override
			public Object convert(Class type, Object value) {
				
				// 判斷
				if (type != Date.class) {
					return null;
				}
				if (value == null || "".equals(value.toString().trim())) {
					return null;
				}
				try {
					// 字串轉換為日期
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  					return sdf.parse(value.toString());
				} catch (ParseException e) {
					throw new RuntimeException(e);
				}
			}
		},Date.class);
		
		// 把表單提交的資料,封裝到物件中
		BeanUtils.copyProperty(admin, "userName", name);
		BeanUtils.copyProperty(admin, "age", age);
		BeanUtils.copyProperty(admin, "birth", birth);
		
		//------ 測試------
		System.out.println(admin);
	}

3.使用提供的日期型別轉換器工具

public void test3() throws Exception {
		// 模擬表單資料
		String name = "userName";
		String age = "20";
		String birth = null;
		
		// 物件
		Admin admin = new Admin();
		
		// 註冊日期型別轉換器:2, 使用元件提供的轉換器工具類
		ConvertUtils.register(new DateLocaleConverter(), Date.class);
				
		// 把表單提交的資料,封裝到物件中
		BeanUtils.copyProperty(admin, "userName", name);
		BeanUtils.copyProperty(admin, "age", age);
		BeanUtils.copyProperty(admin, "birth", birth);
		
		//------ 測試------
		System.out.println(admin);
	}