這裡使用的是Oracle數據庫, 現將日期字符串向表中設值時, 一般使用
preparedStatement.setDate(). (這樣只能存入日期 ),具體做法如下:


/** *//**將日期字符串轉為Java.util.Date類型*/

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

Java.util.Date utilDate = sdf.parse("20071001");


/** *//**將utilDate轉成sqlDate類型*/

Java.sql.Date sqlDate = utilDate.getTime();


/** *//**通過預處理寫入數據庫*/

preparedStatement.setDate(1,sqlDate);

注意:SimpleDateFormat的日期格式“yyyyMMdd”,不能寫成"yyyymmdd",否則將得到的日期只會為01月。
另類取得年月日的方法:

import Java.text.SimpleDateFormat;

import Java.util.*;

java.util.Date date = new Java.util.Date();

//如果希望得到YYYYMMDD的格式SimpleDateFormat

SimpleDateFormat syf=new SimpleDateFormat("yyyyMMDD");

String dateFormat=syf.format(date);

//如果希望分開得到年,月,日SimpleDateFormat

SimpleDateFormat sy=new SimpleDateFormat("yyyy");

SimpleDateFormat sm=new SimpleDateFormat("MM");

SimpleDateFormat sd=new SimpleDateFormat("dd");

String syear=sy.format(date);

String smon=sm.format(date);

String sday=sd.format(date);