001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.dbutils.handlers.properties; 018 019import org.apache.commons.dbutils.PropertyHandler; 020 021import java.sql.Timestamp; 022import java.util.Date; 023 024/** 025 * {@link PropertyHandler} for date fields. Will convert {@link java.sql.Date}, {@link java.sql.Time}, and 026 * {@link java.sql.Timestamp} from SQL types to java types. 027 */ 028public class DatePropertyHandler implements PropertyHandler { 029 @Override 030 public boolean match(final Class<?> parameter, final Object value) { 031 if (value instanceof Date) { 032 final String targetType = parameter.getName(); 033 if ("java.sql.Date".equals(targetType)) { 034 return true; 035 } else 036 if ("java.sql.Time".equals(targetType)) { 037 return true; 038 } else 039 if ("java.sql.Timestamp".equals(targetType) 040 && !Timestamp.class.isInstance(value)) { 041 return true; 042 } 043 } 044 045 return false; 046 } 047 048 @Override 049 public Object apply(final Class<?> parameter, Object value) { 050 final String targetType = parameter.getName(); 051 final Date dateValue = (Date) value; 052 final long time = dateValue.getTime(); 053 054 if ("java.sql.Date".equals(targetType)) { 055 value = new java.sql.Date(time); 056 } else 057 if ("java.sql.Time".equals(targetType)) { 058 value = new java.sql.Time(time); 059 } else 060 if ("java.sql.Timestamp".equals(targetType)) { 061 value = new Timestamp(time); 062 } 063 064 return value; 065 } 066}