Package com. date. demo; Import java. text. ParseException; Import java. text. SimpleDateFormat; Import java. util. Calendar; Import java. util. Date; Public class DateDemo { Public static void main (String args []) { System. out. println ("--------------- obtain the year, month, and day of the current time -----------------"); GetMonthDay (); System. out. println ("--------------- obtain the year, month, and day of the custom time -----------------"); GetMonthDay2Set (); } /** * Get the year, month, and day of the custom time */ Private static void getMonthDay2Set (){ String dateStr = "18:45:39 "; SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss "); Calendar cal = Calendar. getInstance (); Date dt = null; Try { Dt = sdf. parse (dateStr ); Cal. setTime (dt ); } Catch (ParseException e ){ // TODO Auto-generated catch block E. printStackTrace (); } Int year = cal. get (Calendar. YEAR ); Int month = cal. get (Calendar. MONTH) + 1; Int day = cal. get (Calendar. DAY_OF_MONTH ); Int hour = cal. get (Calendar. HOUR_OF_DAY ); Int minute = cal. get (Calendar. MINUTE ); Int second = cal. get (Calendar. SECOND ); System. out. println ("= year =" + year ); System. out. println ("= month =" + month ); System. out. println ("= day =" + day ); System. out. println ("====" + hour ); System. out. println ("====" + minute ); System. out. println ("= seconds =" + second ); } /** * Get the year, month, and day of the current time */ Private static void getMonthDay (){ Calendar cal = Calendar. getInstance (); Int year = cal. get (Calendar. YEAR ); Int month = cal. get (Calendar. MONTH) + 1; Int day = cal. get (Calendar. DAY_OF_MONTH ); Int hour = cal. get (Calendar. HOUR_OF_DAY ); Int minute = cal. get (Calendar. MINUTE ); Int second = cal. get (Calendar. SECOND ); System. out. println ("= year =" + year ); System. out. println ("= month =" + month ); System. out. println ("= day =" + day ); System. out. println ("====" + hour ); System. out. println ("====" + minute ); System. out. println ("= seconds =" + second ); } } |