我們在注冊網(wǎng)站的時(shí)候,往往需要填寫個(gè)人信息,如姓名,年齡,出生日期等,在頁面上的出生日期的值傳遞到后臺(tái)的時(shí)候是一個(gè)字符串,而我們存入數(shù)據(jù)庫的時(shí)候確需要一個(gè)日期類型,反過來,在頁面上顯示的時(shí)候,需要從數(shù)據(jù)庫獲取出生日期,此時(shí)該類型為日期類型,然后需要將該日期類型轉(zhuǎn)為字符串顯示在頁面上,Java的API中為我們提供了日期與字符串相互轉(zhuǎn)運(yùn)的類DateForamt。DateForamt是一個(gè)抽象類,所以平時(shí)使用的是它的子類SimpleDateFormat。SimpleDateFormat有4個(gè)構(gòu)造函數(shù),最經(jīng)常用到是第二個(gè)。
構(gòu)造函數(shù)中pattern為時(shí)間模式,具體有什么模式,API中有說明,如下
1、日期轉(zhuǎn)字符串(格式化)
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; @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)); } } |
2016-10-24
2016-10-24 21:59:06
2016年10月24日 21:59:06
2、字符串轉(zhuǎn)日期(解析)
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)); } } |
Mon Oct 24 21:59:06 CST 2016
在字符串轉(zhuǎn)日期操作時(shí),需要注意給定的模式必須和給定的字符串格式匹配,否則會(huì)拋出java.text.ParseException異常,例如下面這個(gè)就是錯(cuò)誤的,字符串中并沒有給出時(shí)分秒,那么SimpleDateFormat當(dāng)然無法給你憑空解析出時(shí)分秒的值來
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" ; SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); System.out.println(sdf.parse(string)); } } |
不過,給定的模式比字符串少則可以
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" ); System.out.println(sdf.parse(string)); } } |
Mon Oct 24 00:00:00 CST 2016
可以看出時(shí)分秒都是0,沒有被解析,這是可以的。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。