Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store current date and date 1 year from current in java

Tags:

java

date

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?

like image 441
bardockyo Avatar asked Feb 18 '13 23:02

bardockyo


People also ask

How do I get the current year from a date in Java?

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.

How do you add years in Java?

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.

How can I get tomorrow date in dd mm yyyy format in Java?

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.


1 Answers

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

like image 137
iTech Avatar answered Oct 11 '22 09:10

iTech