Java Date Compare compareDate(Date sourceDate, Date targetDate)

Here you can find the source of compareDate(Date sourceDate, Date targetDate)

Description

compare Date

License

Open Source License

Declaration

public static long compareDate(Date sourceDate, Date targetDate) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Main {
    public static long compareDate(Date sourceDate, Date targetDate) {
        long ret = -1;

        if (sourceDate == null && targetDate == null) {
            ret = 0;//from w  w  w. jav a 2 s  . c  om
        } else if (sourceDate == null) {
            ret = -1;
        } else if (targetDate == null) {
            ret = 1;
        } else {
            if (sourceDate.getYear() > targetDate.getYear()) {
                ret = 1;
            } else if (sourceDate.getYear() < targetDate.getYear()) {
                ret = -1;
            } else {
                if (sourceDate.getMonth() > targetDate.getMonth()) {
                    ret = 1;
                } else if (sourceDate.getMonth() < targetDate.getMonth()) {
                    ret = -1;
                } else {
                    if (sourceDate.getDate() > targetDate.getDate()) {
                        ret = 1;
                    } else if (sourceDate.getDate() < targetDate.getDate()) {
                        ret = -1;
                    } else {
                        ret = 0;
                    }
                }
            }
        }
        return ret;
    }

    public static int getYear() {
        Calendar calendar = new GregorianCalendar();
        Date trialTime = new Date();
        calendar.setTime(trialTime);
        return calendar.get(Calendar.YEAR);
    }

    public static int getYear(Date date) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }

    public static int getMonth() {
        Calendar calendar = new GregorianCalendar();
        Date trialTime = new Date();
        calendar.setTime(trialTime);
        return calendar.get(Calendar.MONTH) + 1;
    }

    public static int getMonth(Date date) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) + 1;
    }
}

Related

  1. compareDate(Date date1, Date date2)
  2. compareDate(Date date1, Date date2)
  3. compareDate(Date date1, Date date2)
  4. compareDate(Date date1, Date date2, String pattern)
  5. compareDate(Date first, Date second)
  6. compareDate(Date start, Date end)
  7. compareDate(String begingDate, String endDate, String format)
  8. compareDate(String d1, String d2)
  9. compareDate(String d1, String d2)