通用时间格式化

来源:互联网 发布:认知语言学与人工智能 编辑:程序博客网 时间:2024/06/05 14:55
  为了方便时间格式的转换,可以专门写一个工具类,当需要格式化相应格式的时间时,调用这个类即可
1.//改变格式化后想要某种格式的字符串
/** *将字符串格式yyyyMMdd的字符串转为日期,格式"yyyy-MM-dd" * * @param     sourceFormatStr :当前的时间格式              destFormatStr   :想要转成的时间格式               date           :传入格式化的时间(参数) * @return 返回格式化的日期 * @throws ParseException 分析时意外地出现了错误异常 */public  class   DateTranformTools{    public  static  String   tranFormDateFormat(StringsourceFormatStr, StringdestFormatStr, Stringdate)   {          SimpleDateFormatsdfs=newSimpleDateFormat(sourceFormatStr);          SimpleDateFormatddfs=newSimpleDateFormat(destFormatStr);          DatesTime=null;       try       {
          sTime=sdfs.parse(date);           returnddfs.format(sTime);       }catch(ParseExceptione)       {          e.printStackTrace();       }          return   "";    }
}
如:String   startTime ="20170926";
StringstartTimeStr = TinyTools.tranFormDateFormat("yyyyMMdd","yyyy-MM-dd",startTime)
result为:2017-09-26
StringstartTimeStr = TinyTools.tranFormDateFormat("yyyyMMdd","yyyy年MM月dd日",startTime)
result为:2017年09月26日
其他时间格式转换亦如此


2. 传入一个时间字符串,返回指定格式化后的时间格式
/**    *将字符串格式yyyyMMdd的字符串转为日期,格式"yyyy-MM-dd"    *    * @param date 日期字符串    * @return 返回格式化的日期    * @throws ParseException 分析时意外地出现了错误异常    */   public static String  changeToDateFormat(String date) throws ParseException {       SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");       formatter.setLenient(false);   //设置不对日期       Date newDate= formatter.parse(date);       formatter = new SimpleDateFormat("yyyy-MM-dd");       return formatter.format(newDate);   }