DatePropertyHandler.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.dbutils.handlers.properties;

  18. import java.sql.Timestamp;
  19. import java.util.Date;

  20. import org.apache.commons.dbutils.PropertyHandler;

  21. /**
  22.  * {@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
  23.  * types.
  24.  */
  25. public class DatePropertyHandler implements PropertyHandler {

  26.     private static final String JAVA_SQL_TIMESTAMP = "java.sql.Timestamp";
  27.     private static final String JAVA_SQL_TIME = "java.sql.Time";
  28.     private static final String JAVA_SQL_DATE = "java.sql.Date";

  29.     @Override
  30.     public Object apply(final Class<?> parameter, Object value) {
  31.         final String targetType = parameter.getName();
  32.         final Date dateValue = (Date) value;
  33.         final long time = dateValue.getTime();

  34.         if (JAVA_SQL_DATE.equals(targetType)) {
  35.             value = new java.sql.Date(time);
  36.         } else if (JAVA_SQL_TIME.equals(targetType)) {
  37.             value = new java.sql.Time(time);
  38.         } else if (JAVA_SQL_TIMESTAMP.equals(targetType)) {
  39.             value = new Timestamp(time);
  40.         }

  41.         return value;
  42.     }

  43.     @Override
  44.     public boolean match(final Class<?> parameter, final Object value) {
  45.         if (value instanceof Date) {
  46.             final String targetType = parameter.getName();
  47.             if (JAVA_SQL_DATE.equals(targetType)) {
  48.                 return true;
  49.             }
  50.             if (JAVA_SQL_TIME.equals(targetType)) {
  51.                 return true;
  52.             }
  53.             if (JAVA_SQL_TIMESTAMP.equals(targetType) && !Timestamp.class.isInstance(value)) {
  54.                 return true;
  55.             }
  56.         }

  57.         return false;
  58.     }
  59. }