---
title: "java 日期格式化 将String日期重新格式化成String型"
author: "thinkerAndThinker"
date: "2017-11-13T10:52:50Z"
tags: []
categories: ["Web前端"]
slug: "java-string-string"
draft: false
lastmod: "2017-11-13T10:52:50Z"
id: 2399508
url: "https://javatea.iteye.com/blog/2399508"
---

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

Java代码  [![收藏代码](http://heisetoufa.iteye.com/images/icon_star.png)]()

01. public static void main(String args\[]){
02. String strDate = "2011-11-11 10:11:30.345" ;
03. // 准备第一个模板，从字符串中提取出日期数字
04. String pat1 = "yyyy-MM-dd HH:mm:ss.SSS" ;
05. // 准备第二个模板，将提取后的日期数字变为指定的格式
06. String pat2 = "yyyy年MM月dd日 HH时mm分ss秒SSS毫秒" ;
07. SimpleDateFormat sdf1 = new SimpleDateFormat(pat1) ;        // 实例化模板对象
08. SimpleDateFormat sdf2 = new SimpleDateFormat(pat2) ;        // 实例化模板对象
09. 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代码  [![收藏代码](http://heisetoufa.iteye.com/images/icon_star.png)]()

01. /\**
02. * 将String型格式化,比如想要将2011-11-11格式化成2011年11月11日,就StringPattern("2011-11-11","yyyy-MM-dd","yyyy年MM月dd日").
03. * @param date String 想要格式化的日期
04. * @param oldPattern String 想要格式化的日期的现有格式
05. * @param newPattern String 想要格式化成什么格式
06. * @return String
07. \*/
08. public final String StringPattern(String date, String oldPattern, String newPattern) {
09. 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. }