简体   繁体   中英

Java: Date manipulation

I'm trying to modify the date using SimpleDateFormat and Calendar object. Then writes modified date into my database. The problem is, my method won't compile. It says: Incompatible types String cannot be converted to Date. What did i miss? This is my method

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;dr

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

Details

Question is not clear, but it sounds like you are trying to get the current date, add some number of days (input as text) to determine an “expiration” date, and display that as text.

You are using confusing troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

Getting the current date requires a time zone. For any given moment the date varies around the globe by zone.

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

You can use the JVM's current default time zone. But know that the default can be changed at any moment by any code in any thread of any app within the JVM. So if crucial, ask the user for desired/expected zone.

ZoneId z = ZoneId.systemDefault() ;

To represent a date-only value without a time-of-day and without a time zone, use LocalDate .

LocalDate today = LocalDate.now( z );

Parse the number-of-days text into a long .

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

Add days to your today date.

LocalDate expiration = today.plusDays( days ) ;

To generate a String representing that value in standard ISO 8601 format YYYY-MM-DD, simply call toString .

String output = expiration.toString();

2017-01-23

If your JDBC driver complies with JDBC 4.2 or later, then you can exchange this LocalDate with your database via PreparedStatement::setObject and ResultSet::getObject methods.

For older drivers, convert to/from the java.sql.Date class using new conversion methods added to the old class.

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

LocalDate expiration = sqlDate.toLocalDate();

Tip: Separate the code doing business logic (calculating the expiration) from the user-interface work of gathering input and displaying result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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