Java provides a variety of date representation methods. These include date, timestamp, calendar, and gregoriancalendar. The gregoriancalendar class provides the add () method for date calculation, which can easily calculate the date of several years, months, and days later.
Here is an example:
Package testjava;
Import java. SQL. timestamp;
Import java. Text. simpledateformat;
Import java. util. date;
Import java. util. gregoriancalendar;
Public class datetest {
Public static void main (string [] ARGs ){
Simpledateformat df = new simpledateformat ("yyyy-mm-dd ");
Datetest test = new datetest ();
// Date
Date currentdate = new date ();
System. Out. println ("current date:" + DF. Format (currentdate ));
System. Out. println ("the date after one week is:" + DF. Format (test. nextweek (currentdate )));
System. Out. println ("the date after January 1, January is:" + DF. Format (test. nextmonth (currentdate )));
System. Out. println ("the date after one year is:" + DF. Format (test. nextyear (currentdate )));
// Timestamp
Timestamp currenttime = new timestamp (system. currenttimemillis ());
System. Out. println ("current date:" + DF. Format (currenttime ));
System. Out. println ("the date after one week is:" + DF. Format (test. nextweek (currenttime )));
System. Out. println ("the date after January 1, January is:" + DF. Format (test. nextmonth (currenttime )));
System. Out. println ("the date of one year is:" + DF. Format (test. nextyear (currenttime )));
// Another calculation method, which is difficult to calculate the date of Month and year
Timestamp nexttime = new timestamp (currenttime. gettime () + 7*24*60*60*1000 );
System. Out. println ("current date:" + DF. Format (currenttime ));
System. Out. println ("the date after one week is:" + DF. Format (nexttime ));
}
// Obtain the date of the next week
Public date nextweek (date currentdate ){
Gregoriancalendar Cal = new gregoriancalendar ();
Cal. settime (currentdate );
Cal. Add (gregoriancalendar. date, 7); // Add 7 days to the date
Return Cal. gettime ();
}
// Obtain the date of this Sunday
Public date getsunday (date Monday ){
Gregoriancalendar Cal = new gregoriancalendar ();
Cal. settime (Monday );
Cal. Add (gregoriancalendar. date, 6); // Add 6 days to the date
Return Cal. gettime ();
}
// Obtain the date of the next month
Public date nextmonth (date currentdate ){
Gregoriancalendar Cal = new gregoriancalendar ();
Cal. settime (currentdate );
Cal. Add (gregoriancalendar. month, 1); // Add 1 to the month.
Return Cal. gettime ();
}
// Obtain the date of the next year
Public date nextyear (date currentdate ){
Gregoriancalendar Cal = new gregoriancalendar ();
Cal. settime (currentdate );
Cal. Add (gregoriancalendar. Year, 1); // Add 1 to the year
Return Cal. gettime ();
}
}