java中compareTo比較兩個日期大小

java中compareTo比較兩個日期大小

我們對兩個日期進行比較的時候,或者是日期的string進行比較的時候,以前我一直以爲,如果大於的話compareTo的返回值應該是1,等於的話是0,小於的話是-1,網上很多也是這樣說,但是現實中我程序出錯,最後打出來,看了一下,如果大於的話返回的是正整數,等於是0,小於的話就是負整數,而不僅僅侷限於1,0和-1,以後做比較要注意(這段話出處見此

日期進行比較

源碼

    /**
     * Compares two Dates for ordering.
     *
     * @param   anotherDate   the <code>Date</code> to be compared.
     * @return  the value <code>0</code> if the argument Date is equal to
     *          this Date; a value less than <code>0</code> if this Date
     *          is before the Date argument; and a value greater than
     *      <code>0</code> if this Date is after the Date argument.
     * @since   1.2
     * @exception NullPointerException if <code>anotherDate</code> is null.
     */
    public int compareTo(Date anotherDate) {
        long thisTime = getMillisOf(this);
        long anotherTime = getMillisOf(anotherDate);
        return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1));
    }

例子

package bai.test;

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

import org.junit.Test;

public class CompareTo_Date {

    @Test
    public void test() {
        Calendar c = Calendar.getInstance();

        c.set(2016,5,4);
        Date before =c.getTime();

        c.set(2016,5,5);
        Date now=c.getTime();

        c.set(2016,5,6);
        Date after=c.getTime();

        //before早於now,返回負數,可用於判斷活動開始時間是否到了
        int compareToBefore=before.compareTo(now);
        System.out.println("compareToBefore = "+compareToBefore);

        int compareToIntNow=now.compareTo(now);
        System.out.println("compareToIntNow = "+compareToIntNow);

        //after晚於now,返回正數,可用於判斷活動結束時間是否到了
        int compareToIntAfter=after.compareTo(now);
        System.out.println("compareToIntAfter = "+compareToIntAfter);
    }

}

輸出如下

compareToBefore = -1
compareToIntNow = 0
compareToIntAfter = 1

日期的string進行比較

源碼

    /**
     * Compares two strings lexicographically.
     * The comparison is based on the Unicode value of each character in
     * the strings. The character sequence represented by this
     * <code>String</code> object is compared lexicographically to the
     * character sequence represented by the argument string. The result is
     * a negative integer if this <code>String</code> object
     * lexicographically precedes the argument string. The result is a
     * positive integer if this <code>String</code> object lexicographically
     * follows the argument string. The result is zero if the strings
     * are equal; <code>compareTo</code> returns <code>0</code> exactly when
     * the {@link #equals(Object)} method would return <code>true</code>.
     * <p>
     * This is the definition of lexicographic ordering. If two strings are
     * different, then either they have different characters at some index
     * that is a valid index for both strings, or their lengths are different,
     * or both. If they have different characters at one or more index
     * positions, let <i>k</i> be the smallest such index; then the string
     * whose character at position <i>k</i> has the smaller value, as
     * determined by using the &lt; operator, lexicographically precedes the
     * other string. In this case, <code>compareTo</code> returns the
     * difference of the two character values at position <code>k</code> in
     * the two string -- that is, the value:
     * <blockquote><pre>
     * this.charAt(k)-anotherString.charAt(k)
     * </pre></blockquote>
     * If there is no index position at which they differ, then the shorter
     * string lexicographically precedes the longer string. In this case,
     * <code>compareTo</code> returns the difference of the lengths of the
     * strings -- that is, the value:
     * <blockquote><pre>
     * this.length()-anotherString.length()
     * </pre></blockquote>
     *
     * @param   anotherString   the <code>String</code> to be compared.
     * @return  the value <code>0</code> if the argument string is equal to
     *          this string; a value less than <code>0</code> if this string
     *          is lexicographically less than the string argument; and a
     *          value greater than <code>0</code> if this string is
     *          lexicographically greater than the string argument.
     */
    public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;

        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }

例子

    @Test
    public void test() {
        String date = "2017-07-17 11:03:52";
        System.out.println("compareToBefore1 : "+date.compareTo("2017-06-16 11:03:52"));
        System.out.println("compareToBefore2 : "+date.compareTo("2017-05-16 11:03:52"));
        System.out.println("compareToNow1 : "+date.compareTo("2017-07-17 11:03:52"));
        System.out.println("compareToNow2 : "+date.compareTo("2017-07-17"));
        System.out.println("compareToAfter1 : "+date.compareTo("2017-07-18 11:03:52"));
        System.out.println("compareToAfter2 : "+date.compareTo("2017-09-16 11:03:52"));
    }

輸出如下

compareToBefore1 : 1
compareToBefore2 : 2
compareToNow1 : 0
compareToNow2 : 9
compareToAfter1 : -1
compareToAfter2 : -2
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章