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 java.sql.Timestamp; 020import java.util.Date; 021 022import org.apache.commons.dbutils.PropertyHandler; 023 024/** 025 * {@link PropertyHandler} for date fields. Will convert {@link java.sql.Date}, {@link java.sql.Time}, and {@link java.sql.Timestamp} from SQL types to java 026 * types. 027 */ 028public class DatePropertyHandler implements PropertyHandler { 029 030 private static final String JAVA_SQL_TIMESTAMP = "java.sql.Timestamp"; 031 private static final String JAVA_SQL_TIME = "java.sql.Time"; 032 private static final String JAVA_SQL_DATE = "java.sql.Date"; 033 034 @Override 035 public Object apply(final Class<?> parameter, Object value) { 036 final String targetType = parameter.getName(); 037 final Date dateValue = (Date) value; 038 final long time = dateValue.getTime(); 039 040 if (JAVA_SQL_DATE.equals(targetType)) { 041 value = new java.sql.Date(time); 042 } else if (JAVA_SQL_TIME.equals(targetType)) { 043 value = new java.sql.Time(time); 044 } else if (JAVA_SQL_TIMESTAMP.equals(targetType)) { 045 value = new Timestamp(time); 046 } 047 048 return value; 049 } 050 051 @Override 052 public boolean match(final Class<?> parameter, final Object value) { 053 if (value instanceof Date) { 054 final String targetType = parameter.getName(); 055 if (JAVA_SQL_DATE.equals(targetType)) { 056 return true; 057 } 058 if (JAVA_SQL_TIME.equals(targetType)) { 059 return true; 060 } 061 if (JAVA_SQL_TIMESTAMP.equals(targetType) && !Timestamp.class.isInstance(value)) { 062 return true; 063 } 064 } 065 066 return false; 067 } 068}