Reputation: 491
I am getting the date value from databse through bean. I want to increment the date got from the database by +1 year. Can someone please tell me how can I do this? This is what I have done so far.
if (reviewDate != null || !(reviewDate.equals("0")))
{
//convert reviewDate string to date
Date currentDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(reviewDate);
System.out.println("currentDate = "+currentDate);
//get the current year
int currentMonth = currentDate.getMonth();
int currentDay = currentDate.getDate();
long currentYear = currentDate.getYear();
long currentTime = currentDate.getTime();
System.out.println("current month="+currentMonth);
System.out.println("current day="+currentDay);
System.out.println("current year="+currentYear);
System.out.println("current time="+currentTime);
Date newDate = null;
//increment year
currentYear = currentYear+1;
System.out.println("current year after increment="+currentYear);
//add this to currentDate and assign to newDate
reviewDate = currentMonth + "/" + currentDay + "/" + currentYear + " " + currentTime;
System.out.println("ReviewDate=" + reviewDate);
}
My input is - 04/22/1980 11:30:20 My output should be - 04/22/1981 11:30:20
However, I am getting 3/22/81/325279822000
I think I cannot use calendar because I do not want to increment by current date. Can someone suggest me a working solution for this?
Upvotes: 0
Views: 202
Reputation: 29816
Here is Java 8 solution by java.time
:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class SO25801191 {
public static void main(String[] args) {
System.out.println(getDateAsStringIncrementedByYear("04/22/1980 11:30:20", "MM/dd/yyyy HH:mm:ss", 1));
}
private static String getDateAsStringIncrementedByYear(String inputDateStr, String pattern, long yearsToIncrement) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
LocalDateTime dateTime = LocalDateTime.parse(inputDateStr, formatter);
return dateTime.plusYears(yearsToIncrement).format(formatter);
}
}
Upvotes: 2
Reputation: 35577
You can try this way
String rDate="04/22/1980 11:30:20"; // your received String date
DateFormat df=new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");// date format
Date date=df.parse(rDate);// parse String to date
Calendar calendar=Calendar.getInstance();
calendar.setTime(date); // set calender instance to date value
calendar.add(Calendar.YEAR,1); // add one year to current
System.out.println(df.format(calendar.getTime()));
Out put:
04/22/1981 11:30:20
About Java
Calendar
Upvotes: 3