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

dk.eobjects.metamodel.util.TimeComparator Maven / Gradle / Ivy

Go to download

The eobjects.dk MetaModel is a common domain model, query-engine and optimizer for different kinds of datastores.

The newest version!
/*
 * Copyright 2008 eobjects.dk
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package dk.eobjects.metamodel.util;

import java.util.Comparator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;

/**
 * Compares dates of various formats. Since this class has unchecked generic
 * conversion it can compare java.util.Date, java.sql.Date, java.sql.Time and
 * all the other date types supported by Joda time.
 */
public class TimeComparator implements Comparator {

	private static final Log _log = LogFactory.getLog(TimeComparator.class);
	private static Comparator _instance = new TimeComparator();

	public static Comparator getComparator() {
		return _instance;
	}

	private TimeComparator() {
	}

	public static Comparable getComparable(Object o) {
		final DateTime dt1 = new DateTime(o);
		return new Comparable() {

			public int compareTo(Object o) {
				return _instance.compare(dt1, o);
			}

			@Override
			public String toString() {
				return "TimeComparable[time=" + dt1 + "]";
			}
		};
	}

	public int compare(Object o1, Object o2) {
		try {
			DateTime dt1 = new DateTime(o1);
			DateTime dt2 = new DateTime(o2);
			return dt1.compareTo(dt2);
		} catch (Exception e) {
			_log.error(e);
			throw new RuntimeException(e);
		}
	}
}