2

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?

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks a lot @Alvin. Had no idea it was that easy.
No problem! Accept this as correct answer if it's working by clicking the tick.
There's many answers posted for such qns, here's one example
Yeah, I later realized and deleted my comment but thank you
No problem, always glad to help!
3

You can use Calendar class to manipulate date fields:

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

1 Comment

Thank you @ujulu. I had searched a lot for the answer. Guessed I should have just read up on the Calendar class.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.