All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sql2o.converters.AbstractDateConverter Maven / Gradle / Ivy

There is a newer version: 0.2.6
Show newest version
package org.sql2o.converters;

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

/**
 * Used by sql2o to convert a value from the database into a {@link Date}.
 */
public abstract class AbstractDateConverter implements Converter {
    private final Class classOfDate;
    protected AbstractDateConverter(Class classOfDate) {
        this.classOfDate = classOfDate;
    }

    protected abstract E fromMilliseconds(long millisecond);

    @SuppressWarnings("unchecked")
    public E convert(Object val) throws ConverterException {
        if (val == null){
            return null;
        }

        if (classOfDate.isInstance(val)){
            return (E) val;
        }

        if(val instanceof Date){
            return fromMilliseconds(((Date) val).getTime());
        }

        if (val instanceof Number){
            return fromMilliseconds(((Number) val).longValue());
        }

        throw new ConverterException("Cannot convert type " + val.getClass().toString() + " to java.util.Date");
    }

    public Object toDatabaseParam(Date val) {
        if(val==null) return null;
        return (val instanceof Timestamp)
                ? (Timestamp) val
                :new Timestamp(val.getTime());
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy