您的位置:首页 > 编程语言 > Java开发

jdbc日期处理

2017-10-23 21:49 387 查看
java.sql.Date、Time、Timestamp三个类类用于处理来自数据库的日期,继承于java.util.Date.

java.sql.Date只有年月日;java.sql.Time只有时分秒;java.sql.Timestamp全部含有。
package com.mysql;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import com.mysql.fabric.xmlrpc.base.Data;

/**
* JDBC日期处理
* 1.如何从数据库取出日期并格式化(SimpleDateFormat)
* 2.如何只取出月份(int类型)(Calendar)
* 3.如何取出数据库存的精确时间(Timestamp)
* */
public class TestDate {

public static void main(String[] args) {

Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.获取连接
conn = DriverManager
.getConnection(
"jdbc:mysql://127.0.0.1:3306/itoffer?useUnicode=true&characterEncoding=utf-8&useSSL=false",
"root", "1996");
// 3.执行SQL语句
stmt = conn.createStatement();
rs = stmt
.executeQuery("select applicant_registdate from tb_applicant");
// 4.获取结果集
while (rs.next()) {
// 5.循环输出结果
//一.从数据库取出日期并格式化
Date d = rs.getDate("applicant_registdate");// data只包含日期不包含时分秒
// SimpleDateFormat("yyyy年MM月dd日")用给定的模式和默认语言环境的日期格式符号构造
// SimpleDateFormat。
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
// sdf.format(d) 将给定的 Date 格式化为日期/时间字符串
System.out.println("格式化的Data:"+sdf1.format(d));

//二.只取出月份(int类型)
// getInstance()使用默认时区和语言环境获得一个日历。
Calendar c = Calendar.getInstance();
// setTime(d)使用给定的 Date 设置此 Calendar 的时间。
c.setTime(d);
System.out.println("当前月份:"+c.get(Calendar.MONTH)+1); //此处月份从零开始

//三.取出数据库存的精确时间
Timestamp ts = rs.getTimestamp("applicant_registdate");
SimpleDateFormat sdf2 = new SimpleDateFormat(
"yyyy年MM月dd日HH时mm分ss秒");
System.out.println("格式化的Timestamp:"+sdf2.format(ts));

System.out.println();
}
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 6.关闭
finally {
// 有异常发生也会确保释放资源
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();

}
}

}

}
/*
结果:
格式化的Data:2011年01月01日00时00分00秒
当前月份:01
格式化的Timestamp:2011年01月01日13时14分20秒

格式化的Data:2017年09月09日00时00分00秒
当前月份:81
格式化的Timestamp:2017年09月09日00时00分00秒

格式化的Data:2017年10月14日00时00分00秒
当前月份:91
格式化的Timestamp:2017年10月14日15时08分34秒

格式化的Data:2017年10月14日00时00分00秒
当前月份:91
格式化的Timestamp:2017年10月14日15时54分54秒
*/

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jdbc 日期 api java 数据库