字符串和日期的转换

1、日期转字符串(格式化)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.test.dateFormat;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
import org.junit.Test;
 
public class Date2String {
     @Test
     public void test() {
         Date date = new Date();
         SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
         System.out.println(sdf.format(date));
         sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
         System.out.println(sdf.format(date));
         sdf = new SimpleDateFormat( "yyyy年MM月dd日 HH:mm:ss" );
         System.out.println(sdf.format(date));
     }
}

运行结果

1
2
3
2016 - 10 - 24
2016 - 10 - 24 21 : 59 : 06
2016 10 24 21 : 59 : 06

2、字符串转日期(解析)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.test.dateFormat;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
 
import org.junit.Test;
 
public class String2Date {
     @Test
     public void test() throws ParseException {
         String string = "2016-10-24 21:59:06" ;
         SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
         System.out.println(sdf.parse(string));
     }
}

运行结果

1
Mon Oct 24 21 : 59 : 06 CST 2016

猜你喜欢

转载自www.cnblogs.com/fengnan/p/9971187.html