Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
753 views
in Technique[技术] by (71.8m points)

store current date and date 1 year from current in java

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...