JAVA 處理時(shí)間 - java.sql.Date、java.util.Date與數(shù)據(jù)庫(kù)中的Date字段的轉(zhuǎn)換方法[轉(zhuǎn)]2007年10月30日 星期二 下午 09:341、如何將java.util.Date轉(zhuǎn)化為java.sql.Date?
轉(zhuǎn)化:
java.sql.Date sd;
java.util.Date ud;
//initialize the ud such as ud = new java.util.Date();
sd = new java.sql.Date(ud.getTime());
2、如果要插入到數(shù)據(jù)庫(kù)并且相應(yīng)的字段為Date類型
那么可以用PreparedStatement.setDate(int ,java.sql.Date)方法
其中的java.sql.Date可以用上面的方法得到
也可以用數(shù)據(jù)庫(kù)提供TO_DATE函數(shù)
比如 現(xiàn)有 ud
TO_DATE(new SimpleDateFormat().format(ud,"yyyy-MM-dd HH:mm:ss"),
"YYYY-MM-DD HH24:MI:SS")
注意java中表示格式和數(shù)據(jù)庫(kù)提供的格式的不同
一個(gè)實(shí)際的例子
sql="update tablename set timer=to_date('"+t+"','yyyymmddhh24miss') where ....."
這里的t為變量為類似:20051211131223
3、如何將"yyyy-mm-dd"格式的字符串轉(zhuǎn)換為java.sql.Date
方法1
SimpleDateFormat bartDateFormat =
new SimpleDateFormat("yyyy-MM-dd");
String dateStringToParse = "2007-7-12";
try {
java.util.Date date = bartDateFormat.parse(dateStringToParse);
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
System.out.println(sqlDate.getTime());
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
------------------------------------------------------------
方法2
String strDate = "2002-08-09";
StringTokenizer st = new StringTokenizer(strDate, "-");
java.sql.Date date = new java.sql.Date(Integer.parseInt(st.nextToken()),
Integer.parseInt(st.nextToken()),
Integer.parseInt(st.nextToken()));
java.util.Date和java.sql.Date的異同java.sql.Date,java.sql.Time和java.sql.Timestamp三個(gè)都是java.util.Date的子類(包裝類)。
但是為什么java.sql.Date類型的值插入到數(shù)據(jù)庫(kù)中Date字段中會(huì)發(fā)生數(shù)據(jù)截取呢?
java.sql.Date是為了配合SQL DATE而設(shè)置的數(shù)據(jù)類型。“規(guī)范化”的java.sql.Date只包含年月日信息,時(shí)分秒毫秒都會(huì)清零。格式類似:YYYY-MM-DD。當(dāng)我們調(diào)用ResultSet的getDate()方法來獲得返回值時(shí),java程序會(huì)參照"規(guī)范"的java.sql.Date來格式化數(shù)據(jù)庫(kù)中的數(shù)值。因此,如果數(shù)據(jù)庫(kù)中存在的非規(guī)范化部分的信息將會(huì)被劫取。
在sun提供的ResultSet.java中這樣對(duì)getDate進(jìn)行注釋的:
Retrieves the of the designated column in the current row of this ResultSet object as a “java.sql.Date” object in the Java programming language.
同理。如果我們把一個(gè)java.sql.Date值通過PrepareStatement的setDate方法存入數(shù)據(jù)庫(kù)時(shí),java程序會(huì)對(duì)傳入的java.sql.Date規(guī)范化,非規(guī)范化的部分將會(huì)被劫取。然而,我們java.sql.Date一般由java.util.Date轉(zhuǎn)換過來,如:java.sql.Date sqlDate=new java.sql.Date(new java.util.Date().getTime()).
顯然,這樣轉(zhuǎn)換過來的java.sql.Date往往不是一個(gè)規(guī)范的java.sql.Date.要保存java.util.Date的精確值,
我們需要利用java.sql.Timestamp.
Calendar
Calendar calendar=Calendar.getInstance();
//獲得當(dāng)前時(shí)間,聲明時(shí)間變量
int year=calendar.get(Calendar.YEAR);
//得到年
int month=calendar.get(Calendar.MONTH);
//得到月,但是,月份要加上1
month=month+1;
int date=calendar.get(Calendar.DATE);
//獲得日期
String today=""+year+"-"+month+"-"+date+"";
|