Randy
Randy

Reputation: 23

Calculating date in mysql with java

I'm having trouble, finding out how to calculate or get the date from mysql (using java program) after 1 month of the initial saved date given below:

Date rDate = new Date();
java.sql.Date regDate = new java.sql.Date(rDate.getTime());

I am saving the date into a date column in mysql and I want to have another column which contains the date but one month ahead. In other words I have a registration date and I want to have an expiration date calculated automatically which allows only 1 month. Is it possible?

Upvotes: 2

Views: 79

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338366

java.time

You are using terribly-flawed legacy date-time classes. These were supplanted by the modern java.time classes defined in JSR 310, built into Java 8+.

The java.sql.Date class was replaced by java.time.LocalDate.

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

ZoneId z = ZoneId.of( "America/Edmonton" ) ;
LocalDate today = LocalDate.now( z ) ;

You said:

expiration date calculated automatically which allows only 1 month

LocalDate expiry = today.plusMonths( 1 ) ;

You said:

saving the date into a date column in mysql

Make sure you define your column as a data type akin to the SQL Standard type DATE. In MySQL that would be DATE.

JDBC 4.2 and later requires every JDBC driver to support the java.time types.

Writing:

myPreparedStatement.setObject( … , today ) ;
myPreparedStatement.setObject( … , expiry ) ;

Retrieving:

LocalDate start = myResultSet.getObject( … , LocalDate.class ) ;
LocalDate expiry = myResultSet.getObject( … , LocalDate.class ) ;

Upvotes: 1

ujulu
ujulu

Reputation: 3309

You can use Calendar class to manipulate date fields:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
Date futureDate = cal.getTime();

Upvotes: 3

Alvin
Alvin

Reputation: 408

Grabbing the current date and set it into the Calendar format and add 1 to the month.

You can give this a try.

Date rDate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(rDate);
cal.add(Calendar.MONTH, 1);

Upvotes: 3

Related Questions