简体   繁体   English

Java中的日期比较

[英]Dates comparison in Java

I'm trying to compare two dates with the current date. 我正在尝试将两个日期与当前日期进行比较。 It seems not to work when I try to know if a date is the same as the current date. 当我尝试知道某个日期是否与当前日期相同时,这似乎不起作用。 Here's what I do in my code : 这是我在代码中所做的:

//BeginDate is set earlier

Date myDate= new SimpleDateFormat("dd/MM/yyyy").parse(BeginDate);
Date now = new Date();

    System.out.println("Now : " + now);
    System.out.println("myDate : " + myDate);
    System.out.println("equals : " + myDate.equals(now));
    System.out.println(myDate.compareTo(now));

And I get this in the console : 我在控制台中得到这个:

Now : Thu Dec 29 00:28:45 CET 2011
myDate : Thu Dec 29 00:00:00 CET 2011
equals : false
-1

The first comparison should return true and the second "0" right ? 第一个比较应返回true,第二个比较应返回“ 0”,对吗? Or am I missing something ? 还是我错过了什么?

Comparing dates with either equals() or compareTo() compares the times (hours, minutes, seconds, millis) as well as the dates. 使用equals()或compareTo()比较日期会比较时间(小时,分钟,秒,毫秒)以及日期。 Your test is failing because myDate is midnight today, whereas now is a little later than that. 您的测试失败了,因为myDate今天是午夜,而now则晚了一点。

Your comparison is failing because you need to format now so that both dates have the same format and thus may be compared. 您的比较失败了,因为您需要立即设置格式,以便两个日期具有相同的格式,因此可以进行比较。

Or, if you prefer, you can convert dates into strings and perform the comparison: 或者,如果您愿意,可以将日期转换为字符串并执行比较:

    String beginDate = "28/12/2011";
    Calendar now = Calendar.getInstance();
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    String nowStr = df.format(new Date());
    System.out.println("equals : " + beginDate.equals(nowStr));

Are you specifying the milliseconds when creating the dates? 创建日期时是否指定毫秒? If you are, don't. 如果是,那就不要。 So when creating the dates earlier, only specify the Day, Hour etc, not seconds/milliseconds. 因此,在更早地创建日期时,仅指定天,小时等,而不指定秒/毫秒。

And, change the SimpleDateFormat respectively. 并且,分别更改SimpleDateFormat。 That "should" work. 那“应该”工作。

Date object in Java is nothing but a number that represents milliseconds since January 1, 1970, 00:00:00 GMT. Java中的Date对象不过是代表自1970年1月1日格林尼治标准时间00:00:00以来的毫秒数。 It doesn't have any attribute called day, date, month, year etc. That's because date, month, year varies based on the type of calendar and timezone. 它没有称为日,日,月,年等的任何属性。这是因为日期,月,年根据日历和时区的类型而变化。 These attributes belong to Calendar instance. 这些属性属于Calendar实例。

So, if you have 2 Date objects and you want to compare day of month, month and year then you should create corresponding Calendar instance and compare them separately. 因此,如果您有2个Date对象,并且要比较月,日和年中的某天,则应创建相应的Calendar实例并分别进行比较。

// Parse begin date
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date beginDate = dateFormat.parse(beginDateAsString);
// Create calendar instances
Calendar beginDateCalendar = Calendar.getInstance();
beginDateCalendar.setTime(beginDate);
Calendar todayCalendar = Calendar.getInstance();
// Check Equals
boolean dayEquals = todayCalendar.get(Calendar.DAY_OF_MONTH) == beginDateCalendar
        .get(Calendar.DAY_OF_MONTH);
boolean monthEquals = todayCalendar.get(Calendar.MONTH) == beginDateCalendar
        .get(Calendar.MONTH);
boolean yearEquals = todayCalendar.get(Calendar.YEAR) == beginDateCalendar
        .get(Calendar.YEAR);
// Print Equals
System.out.println(dayEquals && monthEquals && yearEquals);

Above code is cumbersome for the current problem but explains how date operations must be done in JAVA. 上面的代码对于当前问题很麻烦,但说明了如何在JAVA中必须执行日期操作。

If you just want to solve the equals problem you have mentioned then the code below will suffice: 如果您只想解决您提到的平等问题,那么下面的代码就足够了:

String todayAsString = (new SimpleDateFormat("dd/MM/yyyy")).format(new Date());
System.out.println(beginDateAsString.equals(todayAsString));

If you are only going to be dealing with dates between the years 1900 and 2100, there is a simple calculation which will give you the number of days since 1900: 如果您仅要处理1900年到2100年之间的日期,可以通过简单的计算得出自1900年以来的天数:

public static int daysSince1900(Date date) {
    Calendar c = new GregorianCalendar();
    c.setTime(date);

    int year = c.get(Calendar.YEAR) - 1900;
    int month = c.get(Calendar.MONTH) + 1;
    int days = c.get(Calendar.DAY_OF_MONTH);

    if (month < 3) {
        month += 12;
        year--;
    }
    int yearDays = (int) (year * 365.25);
    int monthDays = (int) ((month + 1) * 30.61);

    return (yearDays + monthDays + days - 63);
}

Thus, Date (only) comparison can be achieved by checking if the number of days since 1900 of the 2 dates are equal. 因此,可以通过检查两个日期中自1900年以来的天数是否相等来实现日期(仅)比较。

NOTE: The above method should have code added to check if the dates are outside the valid range (1/1/1900 - 31/12/2099) and throw an IllegalArgumentException. 注意:上面的方法应该添加代码以检查日期是否超出有效范围(1/1/1900-31/12/2099)并引发IllegalArgumentException。

And don't ask me where this calculation came from because we've used it since the early '90s. 而且不要问我这个计算的来源,因为我们从90年代初就开始使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM