比较Java中的两个日期 [英] Compare two dates in Java

查看:37
本文介绍了比较Java中的两个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Java 中比较两个日期.我正在使用这样的代码:

I need to compare two dates in 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 包含 2010-06-30 00:31:40.0
  • today 包含 Wed Jun 30 01:41:25 IST 2010
  • questionDate contains 2010-06-30 00:31:40.0
  • today contains Wed Jun 30 01:41:25 IST 2010

我该如何解决这个问题?

How can I resolve this?

推荐答案

日期相等取决于两个日期等于毫秒.使用 new Date() 创建一个新的 Date 对象永远不会等于过去创建的日期.Joda Time 的 API 简化了日期处理;但是,单独使用 Java 的 SDK:

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. Joda Time's APIs simplify working with dates; however, using the Java's SDK alone:

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(); 
}

这篇关于比较Java中的两个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆