web-dev-qa-db-ja.com

Javaで2つの文字列日付を比較する方法は?

私は以下のような文字列形式の2つの日付を持っています-

String startDate = "2014/09/12 00:00";

String endDate = "2014/09/13 00:00";

StartDateはendDateよりも小さくする必要があります。 startDateはendDateより大きくすることはできません。

これら2つの日付を比較し、それに応じてブール値を返すにはどうすればよいですか?

11
john

それらを実際のDateオブジェクトに変換してから、beforeを呼び出します。

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd h:m");
System.out.println(sdf.parse(startDate).before(sdf.parse(endDate)));

parseParseExceptionをスローするので、このコードブロックでキャッチするか、メソッドシグネチャの一部としてスローされることを宣言する必要があることを思い出してください。

33
Makoto

これは完全に機能するデモです。日付のフォーマットについては、- http://docs.Oracle.com/javase/6/docs/api/Java/text/SimpleDateFormat.html を参照してください

import Java.text.ParseException;
import Java.text.SimpleDateFormat;
import Java.util.Date;
import Java.util.Locale;

public class Dating {

    public static void main(String[] args) {

        String startDate = "2014/09/12 00:00";
        String endDate = "2014/09/13 00:00";

        try {
            Date start = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH)
                    .parse(startDate);
            Date end = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH)
                    .parse(endDate);

            System.out.println(start);
            System.out.println(end);

            if (start.compareTo(end) > 0) {
                System.out.println("start is after end");
            } else if (start.compareTo(end) < 0) {
                System.out.println("start is before end");
            } else if (start.compareTo(end) == 0) {
                System.out.println("start is equal to end");
            } else {
                System.out.println("Something weird happened...");
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}
9
sid smith

比較するために SimpleDateFormat を使用してDateに変換します。

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
Date start = sdf.parse(startDate);
Date end = sdf.parse(endDate);
System.out.println(start.before(end));
4
Jean Logeart

最も簡単で安全な方法は、おそらくこれらの文字列の両方を日付として解析し、それらを比較することです。 SimpleDateFormatを使用して日付に変換し、dateオブジェクトのbeforeメソッドまたはafterメソッドを使用してそれらを比較できます。

2
Kenny Hung

もっと簡単にできると思いますが、

Joda Timeを使用

この日付の解析を簡単に試すことができます:

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm");
DateTime d1 = formatter.parseDateTime(startDate);
DateTime d2 = formatter.parseDateTime(endDate);

Assert.assertTrue(d1.isBefore(d2));
Assert.assertTrue(d2.isAfter(d1));
2
Atais
public class DateComparision
{

    public static void main(String args[]) throws AssertionError, ParseException
    {

        DateFormat df = new SimpleDateFormat("dd-MM-yyyy");

        //comparing date using compareTo method in Java
        System.out.println("Comparing two Date in Java using CompareTo method");

        compareDatesByCompareTo(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
        compareDatesByCompareTo(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
        compareDatesByCompareTo(df, df.parse("02-03-2012"), df.parse("01-02-2012"));

        //comparing dates in Java using Date.before, Date.after and Date.equals
        System.out.println("Comparing two Date in Java using Date's before, after and equals method");

        compareDatesByDateMethods(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
        compareDatesByDateMethods(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
        compareDatesByDateMethods(df, df.parse("02-03-2012"), df.parse("01-02-2012"));

        //comparing dates in Java using Calendar.before(), Calendar.after and Calendar.equals()

        System.out.println("Comparing two Date in Java using Calendar's before, after and equals method");
        compareDatesByCalendarMethods(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
        compareDatesByCalendarMethods(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
        compareDatesByCalendarMethods(df, df.parse("02-03-2012"), df.parse("01-02-2012"));

    }

    public static void compareDatesByCompareTo(DateFormat df, Date oldDate, Date newDate)
    {
        //how to check if date1 is equal to date2
        if (oldDate.compareTo(newDate) == 0)
        {
            System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
        }

        //checking if date1 is less than date 2
        if (oldDate.compareTo(newDate) < 0)
        {
            System.out.println(df.format(oldDate) + " is less than " + df.format(newDate));
        }

        //how to check if date1 is greater than date2 in Java
        if (oldDate.compareTo(newDate) > 0)
        {
            System.out.println(df.format(oldDate) + " is greater than " + df.format(newDate));
        }
    }

    public static void compareDatesByDateMethods(DateFormat df, Date oldDate, Date newDate)
    {
        //how to check if two dates are equals in Java
        if (oldDate.equals(newDate))
        {
            System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
        }

        //checking if date1 comes before date2
        if (oldDate.before(newDate))
        {
            System.out.println(df.format(oldDate) + " comes before " + df.format(newDate));
        }

        //checking if date1 comes after date2
        if (oldDate.after(newDate))
        {
            System.out.println(df.format(oldDate) + " comes after " + df.format(newDate));
        }
    }

    public static void compareDatesByCalendarMethods(DateFormat df, Date oldDate, Date newDate)
    {

        //creating calendar instances for date comparision
        Calendar oldCal = Calendar.getInstance();
        Calendar newCal = Calendar.getInstance();

        oldCal.setTime(oldDate);
        newCal.setTime(newDate);

        //how to check if two dates are equals in Java using Calendar
        if (oldCal.equals(newCal))
        {
            System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
        }

        //how to check if one date comes before another using Calendar
        if (oldCal.before(newCal))
        {
            System.out.println(df.format(oldDate) + " comes before " + df.format(newDate));
        }

        //how to check if one date comes after another using Calendar
        if (oldCal.after(newCal))
        {
            System.out.println(df.format(oldDate) + " comes after " + df.format(newDate));
        }
    }
}

[〜#〜] output [〜#〜]

Comparing two Date in Java using CompareTo method
01-01-2012 and 01-01-2012 are equal to each other
02-03-2012 is less than 04-05-2012
02-03-2012 is greater than 01-02-2012

Comparing two Date in Java using Date's before, after and equals method
01-01-2012 and 01-01-2012 are equal to each other
02-03-2012 comes before 04-05-2012
02-03-2012 comes after 01-02-2012

Comparing two Date in Java using Calendar's before, after and equals method
01-01-2012 and 01-01-2012 are equal to each other
02-03-2012 comes before 04-05-2012
02-03-2012 comes after 01-02-2012
0
Creditto

SimpleDateFormatを使用して、文字列表現をDateのインスタンスに解析します。 getTime()を呼び出してミリ秒を取得します。次に、ミリ秒を比較します。

0
AlexR