Java:日期操作

Java: Date manipulation

我正在尝试使用 SimpleDateFormat 和 Calendar 对象修改日期。然后将修改日期写入我的数据库。问题是,我的方法无法编译。它说:不兼容的类型 String 无法转换为 Date。我错过了什么? 这是我的方法

public Date expiredItem() {

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar expiredDate = Calendar.getInstance();
    expiredDate.add(Calendar.DATE, Integer.parseInt(timeFld.getText()));
    //timeFld is JTextField.getText() casted into int

    // The confusing thing is, below Dialog works as i expected but not on my
    // method return.
    JOptionPane.showMessageDialog(null, "Expiration Date: " +       
    dateFormat.format(expiredDate.getTime()));
    return  dateFormat.format(expiredDate.getTime()); //Erroneous code
}

tl;博士

myPreparedStatement.setObject( 
    … ,
    LocalDate.now( ZoneId.of( "America/Montreal" ) )
             .plusDays( … )
)

详情

问题不清楚,但听起来您正在尝试获取当前日期,添加一些天数(作为文本输入)以确定“到期”日期,并将其显示为文本。

您使用的是令人困惑的麻烦的旧日期时间 classes,它们现在已被遗留,被 java.time classes 取代。

获取当前日期需要时区。对于任何给定时刻,日期在全球范围内因地区而异。

ZoneId z = ZoneId.of( "America/Montreal" );

您可以使用 JVM 当前的默认时区。但是请注意,JVM 中任何应用程序的任何线程中的任何代码都可以随时更改默认值。因此,如果至关重要,请向用户询问 desired/expected 区域。

ZoneId z = ZoneId.systemDefault() ;

要表示没有时间和时区的仅日期值,请使用 LocalDate

LocalDate today = LocalDate.now( z );

将天数文本解析为 long

String input = timeFld.getText() ;
long days = Long.parseLong( input );

为您的 today 日期添加天数。

LocalDate expiration = today.plusDays( days ) ;

要生成表示标准 ISO 8601 格式 YYYY-MM-DD 的值的字符串,只需调用 toString.

String output = expiration.toString();

2017-01-23

如果您的 JDBC 驱动程序符合 JDBC 4.2 或更高版本,那么您可以通过 PreparedStatement::setObjectResultSet::getObject 方法与您的数据库交换此 LocalDate .

对于较旧的驱动程序,使用添加到旧 class 的新转换方法将 to/from 转换为 java.sql.Date class。

java.sql.Date sqlDate = java.sql.Date.valueOf( expiration );

LocalDate expiration = sqlDate.toLocalDate();

提示:将执行业务逻辑(计算到期时间)的代码与收集输入和显示结果的用户界面工作分开。