比较两个包含日期的字符串以检查一个是在另一个之前还是之后

Compare two strings that contain a date to check if one is before or after the other

我已经为客户端-服务器应用程序编写了一些代码,允许服务器为 2 个不同的项目设置 2 个截止日期。这些项目有一个截止时间,服务器应该在该时间到达时显示。

这是我目前的情况:

String[] deadlines = new String[2];

Calendar deadline = Calendar.getInstance();

for(int i = 0; i < 2; i++)
{

    System.out.print("Enter finishing time for item " + (i+1) + " in 24-hr format "); // Item 1
    System.out.print("(e.g. 17:52) :  ");
    String timeString = input.nextLine(); // get input

    String hourString = timeString.substring(0,2);
    int hour = Integer.parseInt(hourString);

    String minString = timeString.substring(3,5);
    int minute = Integer.parseInt(minString);                   

    deadline.set(year,month,date,hour,minute,0);

    deadlines[i] = getDateTime(deadline);

    System.out.print("\nDeadline set for item " + (i+1) + "\n");
    System.out.println(getDateTime(deadline)+ "\n\n");
}

System.out.println("\nServer running...\n");


Calendar now = Calendar.getInstance();

System.out.print(deadlines[0]); // HERE
System.out.print(deadlines[1]); // AND HERE
// getDateTime(now) outputs the same as deadlines[0] + deadlines[1].


while(now.before(deadlines[0]) || now.before(deadlines[1])) // THIS LINE
{
    //System.out.println(getDateTime(now));

    try
    {
        Thread.sleep(2000);
    }
    catch (InterruptedException intEx)
    {

    }

    now = Calendar.getInstance();

    if (now.after(deadlines[0]))
        System.out.println("\n\nDeadline reached" + deadlines[0] + "\n");
    if (now.after(deadlines[1]))
        System.out.println("\n\nDeadline reached" + deadlines[1] + "\n");
}

public static String getDateTime(Calendar dateTime)
{
    //Extract hours and minutes, each with 2 digits
    //(i.e., with leading zeroes if needed)...

    String hour2Digits = String.format("%02d", dateTime.get(Calendar.HOUR_OF_DAY));
    String min2Digits = String.format("%02d", dateTime.get(Calendar.MINUTE));

    return(dateTime.get(Calendar.DATE) 
            + "/" + (dateTime.get(Calendar.MONTH)+1) 
            + "/" + dateTime.get(Calendar.YEAR) 
            + "  "+ hour2Digits + ":" + min2Digits);
}   

我需要检查 now 是否在 deadlines[0]deadlines[1] 的值之前。我怎样才能做到这一点?一定有比将其转换为字符串等更好的方法吗?

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dateTime = f.parseDateTime("2012-01-10 23:13:26");

DateTime now = new Date();

if(now.compareTo(dateTime)<=0){
   // dateTime is in the past
} 

您可以使用 LocalTime#parse,它采用您希望用户输入的确切格式。

String input = "17:52";
LocalTime lt = LocalTime.parse(input); // 17:52

然后将它传递给 LocalDateTime#ofLocalDate

LocalDateTime ldt = LocalDateTime.of(LocalDate.of(year, month, day), lt);

如果需要比较它们,请使用compare()isAfter()isBefore()

while (LocalDateTime.now().isAfter(ldt)){
    // doStuff
}

编辑

如果您想在循环外访问对象,请继续使用相同的数组逻辑。

LocalDateTime[] dateTimes = new LocalDateTime[2];

for (//){
    datesTimes[i] // for example
}