`
thinkerAndThinker
  • 浏览: 276006 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

java 日期格式化 将String日期重新格式化成String型

阅读更多

将String型格式化,比如想要将2011-11-11格式化成2011年11月11日 

Java代码  收藏代码
  1. public static void main(String args[]){    
  2.         String strDate = "2011-11-11 10:11:30.345" ;    
  3.         // 准备第一个模板,从字符串中提取出日期数字    
  4.         String pat1 = "yyyy-MM-dd HH:mm:ss.SSS" ;    
  5.         // 准备第二个模板,将提取后的日期数字变为指定的格式    
  6.         String pat2 = "yyyy年MM月dd日 HH时mm分ss秒SSS毫秒" ;    
  7.         SimpleDateFormat sdf1 = new SimpleDateFormat(pat1) ;        // 实例化模板对象    
  8.         SimpleDateFormat sdf2 = new SimpleDateFormat(pat2) ;        // 实例化模板对象    
  9.         Date d = null ;    
  10.         try{    
  11.             d = sdf1.parse(strDate) ;   // 将给定的字符串中的日期提取出来    
  12.         }catch(Exception e){            // 如果提供的字符串格式有错误,则进行异常处理    
  13.             e.printStackTrace() ;       // 打印异常信息    
  14.         }    
  15.         System.out.println(sdf2.format(d)) ;    // 将日期变为新的格式    
  16.     }    



封装了一下 

Java代码  收藏代码
  1. /**  
  2.      * 将String型格式化,比如想要将2011-11-11格式化成2011年11月11日,就StringPattern("2011-11-11","yyyy-MM-dd","yyyy年MM月dd日"). 
  3.      * @param date String 想要格式化的日期 
  4.      * @param oldPattern String 想要格式化的日期的现有格式 
  5.      * @param newPattern String 想要格式化成什么格式 
  6.      * @return String  
  7.      */   
  8.     public final String StringPattern(String date, String oldPattern, String newPattern) {   
  9.         if (date == null || oldPattern == null || newPattern == null)   
  10.             return "";   
  11.         SimpleDateFormat sdf1 = new SimpleDateFormat(oldPattern) ;        // 实例化模板对象    
  12.         SimpleDateFormat sdf2 = new SimpleDateFormat(newPattern) ;        // 实例化模板对象    
  13.         Date d = null ;    
  14.         try{    
  15.             d = sdf1.parse(date) ;   // 将给定的字符串中的日期提取出来    
  16.         }catch(Exception e){            // 如果提供的字符串格式有错误,则进行异常处理    
  17.             e.printStackTrace() ;       // 打印异常信息    
  18.         }    
  19.         return sdf2.format(d);  
  20.     }   
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics