簡體   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