2

我正在尝试在 Java 中创建一个方法,如果当前时间在设定的时间间隔(startTime 和 endTime)之间,则返回 true。

日期无关紧要。做这个的最好方式是什么?

这是我的尝试,它不起作用:

public boolean isNowBetweenDateTime()
{
    final Date now = new Date();
    return now.after(startTime) && now.before(endTime);
}

检查时间是否在两个 Date 对象内的最佳方法(在 java 中)是什么,忽略年、月日?

4

5 回答 5

3

你的代码看起来不错。只需将now,startTime和的日期设置endTime为一些硬编码值。

于 2012-05-02T10:28:14.440 回答
1
于 2016-08-30T18:30:42.573 回答
0

If you want to ignore the Date and only consider the time of day, consider using Joda-Time's LocalTime, which is designed specifically to hold only the time portion.

Here is an example:

java.util.Date startTime = ... ;
java.util.Date endTime = ... ;

public boolean isNowBetweenDateTime()
{
    // get current time
    final LocalTime now = new LocalTime();

    // convert the java.util.Dates to LocalTimes and then compare
    return now.isAfter(LocalTime.fromDateFields(startTime)) &&
           now.isBefore(LocalTime.fromDateFields(endTime));
}
于 2012-05-02T11:04:41.160 回答
0

如果当前时间介于另外两个时间之间,则此 java 函数返回 true。它忽略年/月/日。

import java.text.*;
import java.util.Date;

public static boolean isNowBetweenHours() throws ParseException
{
    String leftBoundaryHours = "01:00:00";   //01:00 hours, military time.(1AM)
    String rightBoundaryHours = "14:00:00";  //14:00 hours, military time.(2PM)

    //returns true if current time is between 
    //leftBoundaryHours and rightBoundaryHours.

    //This formatter converts a bare string to a date.
    DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");

    //add the hand specified time to 1970-01-01 to create left/right boundaries.
    Date leftTimeBoundary = formatter.parse("1970-01-01 " + leftBoundaryHours);
    Date rightTimeBoundary = formatter.parse("1970-01-01 " + rightBoundaryHours);

    //extract only the hours, minutes and seconds from the current Date.
    DateFormat extract_time_formatter = new SimpleDateFormat("HH:mm:ss");

    //Get the current time, put that into a string, add the 1970-01-01, 
    Date now = formatter.parse("1970-01-01 " + 
        extract_time_formatter.format(new Date()));

    //So it is easy now, with the year, month and day forced as 1970-01-01
    //all you do is make sure now is after left, and now is before right.
    if (now.after(leftTimeBoundary) && now.before(rightTimeBoundary))
        return true;
    else
        return false;
}

像这样调用函数:

try {
    System.out.println(isNowBetweenHours());
} catch (ParseException e) {

}

如果当前时间在01:00小时之后但之前14:00 hours,则返回 true。否则返回false。

于 2013-05-09T16:12:18.647 回答
0

首先,我建议使用日历而不是日期。我之前遇到了一些问题,使用日期。我会以毫秒为单位来比较日期,这是最安全的方法。代码如下:

Date now = new Date();

long startTimeInMillis = startTime.getTime();
long endTimeInMillis = endTime.getTime();
return now.getTime >= startTimeInMillis && now.getTime < endTimeInMillis;
于 2012-05-02T10:41:33.887 回答