For a project, you need to compare the time and period. If it is not convenient to operate in the database, the time operation is placed in the Java program. The following is a string-type time after subtracting one day, one month, and then converting to a string-type time after one year.
Import java. Text. parseexception;
Import java. Text. simpledateformat;
Import java. util. calendar;
Import java. util. date;
Public class du03 {
Public static void main (string [] ARGs ){
String time = "20111224 ";
Try {
Simpledateformat df = new simpledateformat ("yyyymmdd"); // defines the conversion format
Date = DF. parse (time); // convert the string to the time format Using parse
Calendar Cal = calendar. getinstance (); // obtain this class instance.
Cal. settime (date); // convert the date format to the Cal type
Cal. Add (calendar. Date,-1); // minus one for calendar days
Date yesterday = Cal. gettime (); // convert Cal to date yesterday
String yesday = DF. Format (yesterday); // convert date to string format using format
System. Out. println ("yesterday:" + yesday );
Cal. Add (calendar. date, 1 );
Cal. Add (calendar. Month,-1 );
Date lastmonthsameday = Cal. gettime (); // last month
String lastmonth = DF. Format (lastmonthsameday );
System. Out. println ("last month:" + lastmonth );
Cal. Add (calendar. month, 1 );
Cal. Add (calendar. Year,-1 );
Date lastyearsameday = Cal. gettime (); // last year
String lastyear = DF. Format (lastyearsameday );
System. Out. println ("last year:" + lastyear );
} Catch (parseexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
}