Second, the introduction of the date format
The formatting of dates is often used in daily development. For example:
1. Specify the new old date format, format a string date. The key is to use the format () method of the SimpleDateFormat object
1 //Date Full format2 Public StaticString date_format = "Yyyy-mm-dd";3 Public StaticString Date_slash_format = "Yyyy/mm/dd";4 5 /**6 * Format dates according to new and old date formats7 * @paramDatestr8 * @paramFormatold9 * @paramformartnewTen * @return One * @Description: A */ - Publicstring convertdatestring (String datestr,string formatold,string formartnew) { - Try { theSimpleDateFormat sdfnew =NewSimpleDateFormat (formartnew); -SimpleDateFormat Sdfold =NewSimpleDateFormat (formatold); -Date D1 =Sdfold.parse (DATESTR); - returnSdfnew.format (d1); +}Catch(ParseException e) { - return""; + } A } at - /** - * Test - * @paramargs - * @Description: - */ in @Test - Public voidtestconvertdatestring () { toString datestr = "2017/10/31"; +String Newdatestr =convertdatestring (Datestr, Datehelper.date_slash_format,datehelper.date_format); - System.out.println (NEWDATESTR); the}
2. Returns a Date object in the specified time format. The key is to use the parse () method of the SimpleDateFormat object.
public static string Date_slash_format = "YYYY/MM/DD";/** * String to date Object * @param datestr * @param pattern * @return * @Descri Ption: */public Date converstr2date (String datestr,string pattern) {try {simpledateformat SDF = new SimpleDateFormat ( Return Sdf.parse (DATESTR);} catch (ParseException e) {return null;}} /** * Test * @param args * @Description: */@Testpublic void Testconverstr2date () {String datestr = "2017/10/31";D ate str2date = Converstr2date (Datestr, Datehelper.date_slash_format); System.out.println (str2date);}
3. Format the string date in the specified format and return the Calendar object. The key is to convert the string to a Date object and then to use the calendar's SetTime method.
1 /**2 * String to Calendar object3 * @paramInputstr4 * @parampattern5 * @return6 * @Description:7 */8 Public StaticCalendar Cvtstr2calender (String inputstr,string pattern) {9 Try {TenSimpleDateFormat SDF =NewSimpleDateFormat (pattern); OneDate inputdate =Sdf.parse (INPUTSTR); ACalendar cal =calendar.getinstance (); - Cal.settime (inputdate); - returnCal; the}Catch(ParseException e) { - Log.error (E.getmessage ()); - return NULL; - } + -}
Java Programming--date formatting