I have everything setup already to store the current date to a variable in Java. What I am trying to figure out is how to store a date of 1 year after the current date.
import java.util.Date; import java.text.SimpleDateFormat; import java.text.DateFormat; import java.util.Scanner; import java.util.Calendar;
Here is what I have for the current date:
DateFormat newDate = new SimpleDateFormat("MM/dd/yyyy"); Date date = new Date(); startDate = newDate.format(date);
So if it were today for example it would store 2/18/2013. I am trying to store the date 2/18/2014. How would I go about doing this?
To get the previous year in Java, first we need to access the current year using the Year. now(). getValue() method and subtract it with -1 . Note: The getValue() method returns the current year in four-digit(2021) format according to the user's local time.
The plusYears() method of LocalDate class in Java is used to add the number of specified years in this LocalDate and return a copy of LocalDate. This method adds the years field in the following steps: Add the years to the year field. Check if the date after adding years is valid or not.
get(Calendar. DAY_OF_MONTH) + 1; will it display tomorrow's date. or just add one to today's date? For example, if today is January 31.
If you do not want to drag external libraries, just use calendar.add(Calendar.YEAR, 1)
Calendar cal = Calendar.getInstance(); Date today = cal.getTime(); cal.add(Calendar.YEAR, 1); // to get previous year add -1 Date nextYear = cal.getTime();
Note, if the date was 29/Feb/2012
and you added 1 year, you will get 28/Feb/2013
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With