java实现时间的比较

 时间大小的比较以及把String类型的时间转换为Date类是时间在开发中是非常常见的,下面的主要是一个工具方法

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String sTime = "2015-07-13";
        String fTime = "2015-07-15";
        System.out.println(compareDate(stringToDate(fTime), stringToDate(sTime)));
    }

    public static Date stringToDate(String dateString) {
        return stringToDate(dateString, "yyyy-MM-dd");
    }

    public static Date stringToDate(String dateText, String format) {

        DateFormat df = null;
        try {
            if (format == null) {
                df = new SimpleDateFormat();
            } else {
                df = new SimpleDateFormat(format);
            }
            df.setLenient(false);

            return df.parse(dateText);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 时间判断
     * @param firstTime
     * @param secondTime
     * @return 第一个时间早于第二个时间-1;第一个时间等于第二个时间 0 ; 第一个时间晚与第二个时间1
     */
    public static int compareDate(Date firstTime, Date secondTime) {

        long lFirstTime = firstTime.getTime();
        long lsecondTime = secondTime.getTime();
        
        if (lFirstTime < lsecondTime) {
            return -1;
        }else if(lFirstTime > lsecondTime){
            return 1;
        }else{
            return 0;
        }
    }
}