欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java Date與String的相互轉(zhuǎn)換詳解

 更新時(shí)間:2017年02月21日 08:46:43   投稿:lqh  
這篇文章主要介紹了Java Date與String的相互轉(zhuǎn)換詳解的相關(guān)資料,需要的朋友可以參考下

Java Date與String的相互轉(zhuǎn)換詳解

前言:

我們?cè)谧?cè)網(wǎng)站的時(shí)候,往往需要填寫(xiě)個(gè)人信息,如姓名,年齡,出生日期等,在頁(yè)面上的出生日期的值傳遞到后臺(tái)的時(shí)候是一個(gè)字符串,而我們存入數(shù)據(jù)庫(kù)的時(shí)候確需要一個(gè)日期類型,反過(guò)來(lái),在頁(yè)面上顯示的時(shí)候,需要從數(shù)據(jù)庫(kù)獲取出生日期,此時(shí)該類型為日期類型,然后需要將該日期類型轉(zhuǎn)為字符串顯示在頁(yè)面上,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中有說(shuō)明,如下

1、日期轉(zhuǎn)字符串(格式化)

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
2 2016-10-24 21:59:06
3 2016年10月24日 21:59:06

2、字符串轉(zhuǎn)日期(解析)

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ò)誤的,字符串中并沒(méi)有給出時(shí)分秒,那么SimpleDateFormat當(dāng)然無(wú)法給你憑空解析出時(shí)分秒的值來(lái)

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

不過(guò),給定的模式比字符串少則可以

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,沒(méi)有被解析,這是可以的。

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論