首页 > 技术文章 > Date与String之间的转换

nancyzhang 2018-03-01 19:55 原文

(1) 将Date格式化为String   

//日期格式化
public void testFormat(){
      SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
      Date date=new Date();

      String str=sdf.format(date);
      System.out.println(str);
}

补充:format即格式化,格式化即将日期格式化为字符串形式。

 

(2) 将String解析为Date  

//和format方法相反,parse方法用于按照特定格式将表示时间的字符串转换为Date对象
public void testParse() throws Exception{
      String str="2018-01-23";
      SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

      Date date=sdf.parse(str);
      System.out.println(date);  
}

 补充:parse即解析,解析即把字符串解析为日期形式。

推荐阅读