繁体   English   中英

"如何在java中比较两个日期和时间"

[英]How to compare two dates along with time in java

我有两个具有以下格式的Date<\/code><\/strong>对象。

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String matchDateTime = sdf.parse("2014-01-16T10:25:00");
Date matchDateTime = null;

try {
    matchDateTime = sdf.parse(newMatchDateTimeString);
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

// get the current date
Date currenthDateTime = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date dt = new Date();
String currentDateTimeString = dateFormat.format(dt);
Log.v("CCCCCurrent DDDate String is:", "" + currentDateTimeString);

try {                   
    currenthDateTime = sdf.parse(currentDateTimeString);
} catch (ParseException e) {
    // TODO Auto-generated catch block 
    e.printStackTrace();
}

由于Date<\/code>实现了Comparable<Date><\/code> ,因此很简单:

date1.compareTo(date2);

另一种选择是......

将两个日期转换为毫秒,如下所示

Date d = new Date();
long l = d.getTime();

使用compareTo()<\/code><\/strong><\/a>

返回值<\/strong>

如果参数 Date 等于此 Date,则为 0; 如果此 Date 在 Date 参数之前,则值小于 0; 如果此 Date 在 Date 参数之后,则值大于 0。

喜欢<\/strong>

if(date1.compareTo(date2)>0) 

另一种选择是Joda-Time<\/a> 。

使用日期时间

DateTime date = new DateTime(new Date());
date.isBeforeNow();
or
date.isAfterNow();
 // Get calendar set to the current date and time
Calendar cal = Calendar.getInstance();

// Set time of calendar to 18:00
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

// Check if current time is after 18:00 today
boolean afterSix = Calendar.getInstance().after(cal);

if (afterSix) {
    System.out.println("Go home, it's after 6 PM!");
}
else {
    System.out.println("Hello!");
}

其他答案通常是正确的并且都已过时。 请务必使用现代 Java 日期和时间 API java.time 进行日期和时间工作。 与 2014 年 2 月提出此问题时的情况相比,使用 java.time 时,您的工作也变得容易得多。

    String dateTimeString = "2014-01-16T10:25:00";
    LocalDateTime dateTime = LocalDateTime.parse(dateTimeString);
    LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());

    if (dateTime.isBefore(now)) {
        System.out.println(dateTimeString + " is in the past");
    } else if (dateTime.isAfter(now)) {
        System.out.println(dateTimeString + " is in the future");
    } else {
        System.out.println(dateTimeString + " is now");
    }

暂无
暂无

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

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