简体   繁体   English

无限循环尝试遍历Java中的日期

[英]Infinite loop trying to iterate through dates in Java

I'm trying to iterate through dates without success as an inifite loop happens and it won't stop creating records in the database. 我试图遍历日期而没有成功,因为发生了无限循环,并且它不会停止在数据库中创建记录。 Why? 为什么?

I have the following method which increments by one the date passed as a parameter and then return it updated. 我有以下方法,该方法将作为参数传递的日期加1,然后将其更新。

public static Date addDays(Date date, int days) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.DATE, days);
    return cal.getTime();
}

And then I use it in a for-loop this way... 然后我以这种方式在for循环中使用它...

for (Date initDate = fromDate; initDate.before(toDate); addDays(initDate, 1)) {
    // Do something...
}

fromDate and toDate are values from a JTextField parsed into sql.Date this way. fromDate和toDate是JTextField中解析为sql.Date的值。

private java.sql.Date fechaParser(String f) {
    SimpleDateFormat formatDate = new SimpleDateFormat("dd/MM/yyyy");
    Date date;

    try {
        date = formatDate.parse(f);
        java.sql.Date sqlDate = new java.sql.Date(date.getTime());

        return sqlDate;
    } catch (ParseException e) {
        JOptionPane.showMessageDialog(null, "Wrong date format.");
        e.printStackTrace();
    }

    return null;
}

Your addDays() function returns a new date instead of changing the argument one. 您的addDays()函数返回一个新日期,而不是更改参数1。

Thus you need to change the increment part of your for-loop from this: 因此,您需要从此更改for循环的增量部分:

for ( ...; addDays(initDate, 1)) { ...

to this: 对此:

for ( ...; initDate = addDays(initDate, 1)) { ...

The accepted Answer is correct. 接受的答案是正确的。

As of Java 8 and later, the java.util.Date/.Calendar classes are now outmoded. 从Java 8和更高版本开始,java.util.Date / .Calendar类现在已过时。

java.time java.time

The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. Java 8和更高版本中内置的java.time框架取代了麻烦的旧java.util.Date/.Calendar类。 The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. 新课程的灵感取自于成功的Joda-Time框架,该框架旨在作为其继任者,其概念相似但经过重新架构。 Defined by JSR 310 . JSR 310定义。 Extended by the ThreeTen-Extra project. ThreeTen-Extra项目扩展。 See the Tutorial . 请参阅教程

First we define a formatter using a pattern to match our expected input String. 首先,我们使用模式来定义格式化程序以匹配我们期望的输入String。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

The java.time framework includes a class to represent a date-only value, without time-of-day: LocalDate . java.time框架包括一个用于表示仅日期值的类,而不包含time:of-day: LocalDate A static method on that class can parse. 该类上的静态方法可以解析。

String input = "05/07/2013";
LocalDate localDate_Start = LocalDate.parse( input , formatter );

If the user gives us bad text input, the parse method throws a DateTimeParseException . 如果用户为我们提供了错误的文本输入,则parse方法将引发DateTimeParseException So we should catch and handle that exception. 因此,我们应该捕获并处理该异常。

try{ 
    LocalDate localDate_Start = LocalDate.parse( input , formatter );
} catch ( DateTimeParseException e ) {
    // … handle the exception …
}

The LocalDate class includes a plusDays method to add days. LocalDate类包括一个plusDays方法来添加天数。

LocalDate localDate_Stop = localDate_Start.plusDays( someNumberOfDays );

By the way, in date-time work we commonly use the Half-Open approach where the beginning is inclusive while the ending is exclusive. 顺便说一句,在日期时间工作中,我们通常使用“半开放式”方法,其中开始是包容性的,而结尾是排他性的。 For example a week would run from a Monday up to, but not including, the following Monday. 例如,一周将从星期一开始,直到但不包括下一个星期一。

A while loop makes more sense to me than your use of a for loop 与您使用for循环相比, while循环对我而言更有意义

To do some database work we must convert from java.time.LocalDate to java.sql.Date. 为了完成一些数据库工作,我们必须将java.time.LocalDate转换为java.sql.Date。 Someday JDBC drivers will be updated to directly handle java.time types but until then we must covert. 有朝一日,JDBC驱动程序将被更新以直接处理java.time类型,但是在那之前,我们必须隐蔽。 Look for newly added conversion methods such as java.sql.Date.valueOf( LocalDate localDate ) . 查找新添加的转换方法,例如java.sql.Date.valueOf( LocalDate localDate )

LocalDate localDate = localDate_Start;
while( localDate.isBefore( localDate_Stop ) ) {
    // Do some database work.
    // Until JDBC drivers updated to handle java.time types, convert to java.sql type.
    java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
    // … do you database work.

    // Prepare for next iteration of this 'while' loop.
    localDate = localDate.plusDays( 1 );
}

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

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