简体   繁体   English

比较Java中的两个日期

[英]Compare two dates in Java

I need to compare two dates in java. 我需要比较java中的两个日期。 I am using the code like this: 我正在使用这样的代码:

Date questionDate = question.getStartDate();
Date today = new Date();

if(today.equals(questionDate)){
    System.out.println("Both are equals");
}

This is not working. 这不起作用。 The content of the variables is the following: 变量的内容如下:

  • questionDate contains 2010-06-30 00:31:40.0 questionDate包含2010-06-30 00:31:40.0
  • today contains Wed Jun 30 01:41:25 IST 2010 today包含Wed Jun 30 01:41:25 IST 2010

How can I resolve this? 我该如何解决这个问题?

Date equality depends on the two dates being equal to the millisecond. 日期相等性取决于两个日期等于毫秒。 Creating a new Date object using new Date() will never equal a date created in the past. 使用new Date()创建一个新的Date对象永远不会等于过去创建的日期。 Joda Time 's APIs simplify working with dates; Joda Time的API简化了日期工作; however, using the Java's SDK alone: 但是,仅使用Java的SDK:

if (removeTime(questionDate).equals(removeTime(today)) 
  ...

public Date removeTime(Date date) {    
    Calendar cal = Calendar.getInstance();  
    cal.setTime(date);  
    cal.set(Calendar.HOUR_OF_DAY, 0);  
    cal.set(Calendar.MINUTE, 0);  
    cal.set(Calendar.SECOND, 0);  
    cal.set(Calendar.MILLISECOND, 0);  
    return cal.getTime(); 
}

I would use JodaTime for this. 我会用JodaTime来做这件事。 Here is an example - lets say you want to find the difference in days between 2 dates. 这是一个例子 - 假设您想要找到两个日期之间的天数差异。

DateTime startDate = new DateTime(some_date); 
DateTime endDate = new DateTime(); //current date
Days diff = Days.daysBetween(startDate, endDate);
System.out.println(diff.getDays());

JodaTime can be downloaded from here . JodaTime可以从这里下载。

It's not clear to me what you want, but I'll mention that the Date class also has a compareTo method, which can be used to determine with one call if two Date objects are equal or (if they aren't equal) which occurs sooner. 我不清楚你想要什么,但我会提到Date类还有一个compareTo方法,如果两个Date对象相等或者(如果它们不相等),可以用一个调用来确定更早。 This allows you to do something like: 这允许您执行以下操作:

switch (today.compareTo(questionDate)) {
    case -1:  System.out.println("today is sooner than questionDate");  break;
    case 0:   System.out.println("today and questionDate are equal");  break;
    case 1:   System.out.println("today is later than questionDate");  break;
    default:  System.out.println("Invalid results from date comparison"); break;
}

It should be noted that the API docs don't guarantee the results to be -1, 0, and 1, so you may want to use if-elses rather than a switch in any production code. 应该注意的是,API文档不保证结果为-1,0和1,因此您可能希望在任何生产代码中使用if-elses而不是switch。 Also, if the second date is null, you'll get a NullPointerException, so wrapping your code in a try-catch may be useful. 此外,如果第二个日期为null,您将获得NullPointerException,因此将代码包装在try-catch中可能很有用。

The easiest way to compare two dates is converting them to numeric value (like unix timestamp). 比较两个日期的最简单方法是将它们转换为数值(如unix时间戳)。

You can use Date.getTime() method that return the unix time. 您可以使用返回unix时间的Date.getTime()方法。

Date questionDate = question.getStartDate();
Date today = new Date();
if((today.getTime() == questionDate.getTime())) {
    System.out.println("Both are equals");
}

it is esy using time.compareTo(currentTime) < 0 它是esy使用time.compareTo(currentTime) < 0

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class MyTimerTask {
    static Timer singleTask = new Timer();

    @SuppressWarnings("deprecation")
    public static void main(String args[]) {
        // set download schedule time
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 9);
        calendar.set(Calendar.MINUTE, 54);
        calendar.set(Calendar.SECOND, 0);
        Date time = (Date) calendar.getTime();
        // get current time
        Date currentTime = new Date();
        // if current time> time schedule set for next day
        if (time.compareTo(currentTime) < 0) {

            time.setDate(time.getDate() + 1);
        } else {
            // do nothing
        }
        singleTask.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("timer task is runing");
            }
        }, time);

    }

}

java.time java.time

In Java 8 there is no need to use Joda-Time as it comes with a similar new API in the java.time package. 在Java 8中,不需要使用Joda-Time,因为它在java.time包中附带了类似的新API。 Use the LocalDate class. 使用LocalDate类。

LocalDate date = LocalDate.of(2014, 3, 18);
LocalDate today = LocalDate.now();

Boolean isToday = date.isEqual( today );

You can ask for the span of time between the dates with Period class. 您可以询问具有Period类的日期之间的时间跨度。

Period difference = Period.between(date, today);

LocalDate is comparable using equals and compareTo as it holds no information about Time and Timezone. LocalDate可以使用equalscompareTo比较,因为它不包含有关时间和时区的信息。


About java.time 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . 这些类取代了麻烦的旧遗留日期时间类,如java.util.DateCalendarSimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参阅Oracle教程 And search Stack Overflow for many examples and explanations. 并搜索Stack Overflow以获取许多示例和解释。 Specification is JSR 310 . 规范是JSR 310

Where to obtain the java.time classes? 从哪里获取java.time类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目是未来可能添加到java.time的试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

The following will return true if two Calendar variables have the same day of the year. 如果两个Calendar变量具有一年中的同一天,则以下内容将返回true。

  public boolean isSameDay(Calendar c1, Calendar c2){
    final int DAY=1000*60*60*24;
    return ((c1.getTimeInMillis()/DAY)==(c2.getTimeInMillis()/DAY));
  } // end isSameDay

Here is an another answer: You need to format the tow dates to fit the same fromat to be able to compare them as string. 这是另一个答案:您需要格式化两个日期以适应相同的fromat,以便能够将它们作为字符串进行比较。

    Date questionDate = question.getStartDate();
    Date today = new Date();

    SimpleDateFormat dateFormatter = new SimpleDateFormat ("yyyy/MM/dd");

    String questionDateStr = dateFormatter.format(questionDate);
    String todayStr = dateFormatter.format(today);

    if(questionDateStr.equals(todayStr)) {
        System.out.println("Both are equals");
    }
public static double periodOfTimeInMillis(Date date1, Date date2) {
    return (date2.getTime() - date1.getTime());
}

public static double periodOfTimeInSec(Date date1, Date date2) {
    return (date2.getTime() - date1.getTime()) / 1000;
}

public static double periodOfTimeInMin(Date date1, Date date2) {
    return (date2.getTime() - date1.getTime()) / (60 * 1000);
}

public static double periodOfTimeInHours(Date date1, Date date2) {
    return (date2.getTime() - date1.getTime()) / (60 * 60 * 1000);
}

public static double periodOfTimeInDays(Date date1, Date date2) {
    return (date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000L);
}
public long compareDates(Date exp, Date today){

        long b = (exp.getTime()-86400000)/86400000;
        long c = (today.getTime()-86400000)/86400000;
        return b-c;
    }

This works for GregorianDates. 这适用于GregorianDates. 86400000 are the amount of milliseconds in a day, this will return the number of days between the two dates. 86400000是一天中的毫秒数,这将返回两个日期之间的天数。

This is a very old post though sharing my work. 这是一篇非常古老的帖子,虽然分享我的作品。 Here is a little trick to do so 这是一个小技巧

DateTime dtStart = new DateTime(Dateforcomparision); 
DateTime dtNow = new DateTime(); //current date

if(dtStart.getMillis() <= dtNow.getMillis())
{
   //to do
}

use comparator as per your requirement 根据您的要求使用比较器

in my case, I just had to do something like this : 在我的情况下,我只需要做这样的事情:

date1.toString().equals(date2.toString())

And it worked! 它奏效了!

It works best.... 它效果最好......

Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();

cal1.setTime(date1);
cal2.setTime(date2);

boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);

Here's what you can do for say yyyy-mm-dd comparison: 以下是你可以做的yyyy-mm-dd比较:

GregorianCalendar gc= new GregorianCalendar();
gc.setTimeInMillis(System.currentTimeMillis());
gc.roll(GregorianCalendar.DAY_OF_MONTH, true);

Date d1 = new Date();
Date d2 = gc.getTime();

SimpleDateFormat sf= new SimpleDateFormat("yyyy-MM-dd");

if(sf.format(d2).hashCode() < sf.format(d1).hashCode())
{
    System.out.println("date 2 is less than date 1");
}
else
{
    System.out.println("date 2 is equal or greater than date 1");
}

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

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