Many (constructor) methods under java. util. date have been identified as "obsolete" methods. It is officially recommended to use the calendar class to process date operations. The following is an example:
Import Java. text. simpledateformat; import Java. util. calendar; import Java. util. date; public class helloworld {public static void main (string [] ARGs) {// specify the time output format simpledateformat SDF = new simpledateformat ("yyyy-mm-dd hh: mm: SS "); Date dt = new date (); system. out. println ("current time:" + SDF. format (DT); Calendar rightnow = calendar. getinstance (); rightnow. settime (DT); rightnow. add (calendar. year,-1); // The date minus 1 year system. out. println ("minus 1 year:" + SDF. format (rightnow. gettime (); rightnow. add (calendar. month, 3); // (in the result above) plus 3 months of system. out. println ("plus 3 months:" + SDF. format (rightnow. gettime (); rightnow. add (calendar. day_of_year, 10); // (in the result above) plus 10 days of system. out. println ("plus 10 days:" + SDF. format (rightnow. gettime ()));}}
Output result:
Current Time: 09:40:49
Minus 1 year: 09:40:49
Plus 3 months: 09:40:49
Plus 10 days: 09:40:49
----------------------------------------------
If you want to split the parts of a date (such as year, month, day, week...), it is also easy:
1 Date dt = New Date (); 2 Calendar calendar = Calendar. getinstance (); 3 Calendar. settime (DT ); 4 System. Out. println ("current date:" + New Simpledateformat ("yyyy-mm-dd hh: mm: SS"). Format (DT )); // Current date: 16:22:37 5 System. Out. println ("year:" + calendar. Get (calendar. Year )); // Year: 2013 6 System. Out. println ("month:" + (calendar. Get (calendar. month) + 1 )); // Month: 2-Note: month starts from 0 7 System. Out. println ("day:" + calendar. Get (calendar. Date )); // Day: 28 8 System. Out. println ("hour (12 hour):" + calendar. Get (calendar. Hour )); // Hour: 4 (12-hour) 9 System. Out. println ("hour (in 24-hour format):" + calendar. Get (calendar. hour_of_day )); // Hour: 16 (in 24-hour format) 10 System. Out. println ("points:" + calendar. Get (calendar. Minute )); // Minute: 30 11 System. Out. println ("seconds:" + calendar. Get (calendar. Second )); // Seconds: 19 12 System. Out. println ("the current month" + calendar. Get (calendar. week_of_month) + "Week "); // WEEK 1 of this month 13 System. Out. println ("the current year" + calendar. Get (calendar. week_of_year) + "Week "); // WEEK 1 of this year