Java中Date與String相互轉換的方法_java

來源:互聯網
上載者:User

我們在註冊網站的時候,往往需要填寫個人資訊,如姓名,年齡,出生日期等,在頁面上的出生日期的值傳遞到背景時候是一個字串,而我們存入資料庫的時候確需要一個日期類型,反過來,在頁面上顯示的時候,需要從資料庫擷取出生日期,此時該類型為日期類型,然後需要將該日期類型轉為字串顯示在頁面上,Java的API中為我們提供了日期與字串相互轉運的類DateForamt。DateForamt是一個抽象類別,所以平時使用的是它的子類SimpleDateFormat。SimpleDateFormat有4個建構函式,最經常用到是第二個。

建構函式中pattern為時間模式,具體有什麼模式,API中有說明,如下

1、日期轉字串(格式化)

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));  }}

2016-10-24
2016-10-24 21:59:06
2016年10月24日 21:59:06

2、字串轉日期(解析)

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

在字串轉日期操作時,需要注意給定的模式必須和給定的字串格式匹配,否則會拋出java.text.ParseException異常,例如下面這個就是錯誤的,字串中並沒有給出時分秒,那麼SimpleDateFormat當然無法給你憑空解析出時分秒的值來

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));  }}

不過,給定的模式比字串少則可以

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

可以看出時分秒都是0,沒有被解析,這是可以的。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.