Java Tutorial/Database/Date Time Timestamp
Содержание
- 1 Convert a java.sql.Timestamp Object to a java.util.Date Object?
- 2 Convert a String Date Such as 10 to a java.sql.Date Object?
- 3 Convert a Timestamp to Month-Day-Year
- 4 Convert into java.sql.Time into java.util.Calendar
- 5 Creating java.sql.Date Using GregorianCalendar
- 6 Creating java.sql.Date Using java.util.Calendar
- 7 Creating java.sql.Date Using java.util.Date
- 8 Creating java.sql.Date Using the java.sql.Date.valueOf() Method
- 9 Get a Date for a Specific Time Zone
- 10 Get a Date Label from a java.sql.Timestamp Object
- 11 Get Date value from ResultSet
- 12 Get the Current Date as a java.util.Date Object
- 13 Get the Current Timestamp as a java.sql.Time Object?
- 14 Get TIMESTAMP value from ResultSet
- 15 Get TIME value from ResultSet
- 16 Getting a Timestamp Object Using java.util.Date
- 17 Getting a Timestamp Object Using System.currentTimeMillis()
- 18 Insert Date value
- 19 Insert TIMESTAMP value
- 20 Insert TIME value
- 21 Make a java.sql.Timestamp Object for a Given Year, Month, Day, Hour
- 22 Returns a java.sql.Timestamp equal to the current time
- 23 Working with Date, Time, and Timestamp in JDBC
Convert a java.sql.Timestamp Object to a java.util.Date Object?
public static java.util.Date toDate(java.sql.Timestamp timestamp) {
long milliseconds = timestamp.getTime() + (timestamp.getNanos() / 1000000);
return new java.util.Date(milliseconds);
}
Convert a String Date Such as 10 to a java.sql.Date Object?
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class MainClass {
public static void main(String[] args) throws ParseException {
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
String date = "2003/01/10";
java.util.Date utilDate = formatter.parse(date);
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("date:" + date);
System.out.println("sqlDate:" + sqlDate);
} catch (ParseException e) {
System.out.println(e.toString());
e.printStackTrace();
}
}
}
date:2003/01/10 sqlDate:2003-01-10
Convert a Timestamp to Month-Day-Year
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
public class MainClass {
private static final SimpleDateFormat monthDayYearformatter = new SimpleDateFormat(
"MMMMM dd, yyyy");
private static final SimpleDateFormat monthDayformatter = new SimpleDateFormat("MMMMM dd");
public static String timestampToMonthDayYear(Timestamp timestamp) {
if (timestamp == null) {
return null;
} else {
return monthDayYearformatter.format((java.util.Date) timestamp);
}
}
public static String timestampToMonthDay(Timestamp timestamp) {
if (timestamp == null) {
return null;
} else {
return monthDayformatter.format((java.util.Date) timestamp);
}
}
public static java.sql.Timestamp getTimestamp() {
java.util.Date today = new java.util.Date();
return new java.sql.Timestamp(today.getTime());
}
}
Convert into java.sql.Time into java.util.Calendar
import java.sql.Time;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* Provides methods helpful in making object conversions not provided for by the
* Sun or MyFaces distributions.
*
* @author
*
*/
public class ConversionUtil {
/**
* convert into java.sql.Time (or into java.util.Calendar
*
* @param date
* The date containing the time.
* @param am
* Whether this should be am (true) or pm (false)
* @return
*/
public static Time convertDateToTime(Date date, boolean am) {
if (date == null) {
return null;
}
Calendar cal = new GregorianCalendar();
cal.setTime(date);
int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
if (am) {
// Check to make sure that the hours are indeed am hours
if (hourOfDay > 11) {
cal.set(Calendar.HOUR_OF_DAY, hourOfDay - 12);
date.setTime(cal.getTimeInMillis());
}
} else {
// Check to make sure that the hours are indeed pm hours
if (cal.get(Calendar.HOUR_OF_DAY) < 11) {
cal.set(Calendar.HOUR_OF_DAY, hourOfDay + 12);
date.setTime(cal.getTimeInMillis());
}
}
return new Time(date.getTime());
}
}
Creating java.sql.Date Using GregorianCalendar
import java.util.Calendar;
import java.util.GregorianCalendar;
public class MainClass {
public static void main(String[] args) {
Calendar calendar = new GregorianCalendar(2000, // year
10, // month
1); // day of month
java.sql.Date date = new java.sql.Date(calendar.getTimeInMillis());
}
}
Creating java.sql.Date Using java.util.Calendar
import java.util.Calendar;
public class MainClass {
public static void main(String[] args) {
// get a calendar using the default time zone and locale.
Calendar calendar = Calendar.getInstance();
// set Date portion to January 1, 1970
calendar.set(Calendar.YEAR, 1970);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DATE, 1);
// normalize the object
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
java.sql.Date javaSqlDate = new java.sql.Date(calendar.getTime().getTime());
}
}
Creating java.sql.Date Using java.util.Date
public class MainClass {
public static void main(String[] args) {
java.util.Date today = new java.util.Date();
System.out.println(new java.sql.Date(today.getTime()));
}
}
Creating java.sql.Date Using the java.sql.Date.valueOf() Method
The java.sql.Date object"s valueOf() method accepts a String, which must be the date in JDBC time escape format: YYYY-MM-DD.
public class MainClass {
public static void main(String[] args) {
String date = "2000-11-01";
java.sql.Date javaSqlDate = java.sql.Date.valueOf(date);
}
}
Get a Date for a Specific Time Zone
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Calendar;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getConnection();
Statement st = conn.createStatement();
st.executeUpdate("create table survey (id int,myDate DATE );");
String INSERT_RECORD = "insert into survey(id, myDate) values(?, ?)";
PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);
pstmt.setString(1, "1");
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
pstmt.setDate(2, sqlDate);
pstmt.executeUpdate();
ResultSet rs = st.executeQuery("SELECT * FROM survey");
Calendar cal = Calendar.getInstance();
// get the TimeZone for "America/Los_Angeles"
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
cal.setTimeZone(tz);
while (rs.next()) {
// the JDBC driver will use the time zone information in
// Calendar to calculate the date, with the result that
// the variable dateCreated contains a java.sql.Date object
// that is accurate for "America/Los_Angeles".
java.sql.Date dateCreated = rs.getDate(2, cal);
System.out.println(dateCreated);
}
rs.close();
st.close();
conn.close();
}
private static Connection getConnection() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
String url = "jdbc:hsqldb:mem:data/tutorial";
return DriverManager.getConnection(url, "sa", "");
}
}
Get a Date Label from a java.sql.Timestamp Object
import java.sql.Timestamp;
public class MainClass {
private static final long One_Day_In_Milliseconds = 86400000;
public static final String DATE_LABEL_TODAY = "Today";
public static final String DATE_LABEL_YESTERDAY = "Yesterday";
public static final String DATE_LABEL_THIS_MONTH = "This Month";
public static final String DATE_LABEL_OLDER = "Older";
public static final String DATE_LABEL_NONE = "";
public static java.sql.Timestamp getTimestamp() {
java.util.Date today = new java.util.Date();
return new java.sql.Timestamp(today.getTime());
}
public static String getDateLabel(java.sql.Timestamp ts, java.sql.Timestamp now) {
long tsTime = ts.getTime();
long nowTime = now.getTime();
long quotient = (nowTime - tsTime) / One_Day_In_Milliseconds;
if (quotient < 1) {
return DATE_LABEL_TODAY;
} else if (quotient < 2) {
return DATE_LABEL_YESTERDAY;
} else if (quotient < 30) {
return DATE_LABEL_THIS_MONTH;
} else {
return DATE_LABEL_OLDER;
}
}
public static void main(String[] args) {
java.sql.Timestamp now = getTimestamp();
java.sql.Timestamp ts1 = getTimestamp();
System.out.println(getDateLabel(ts1, now));
System.out.println(ts1.toString());
System.out.println("-------------");
// timestamp in format yyyy-mm-dd hh:mm:ss.fffffffff
java.sql.Timestamp ts22 = java.sql.Timestamp.valueOf("2007-01-06 09:01:10");
System.out.println(getDateLabel(ts22, now));
System.out.println(ts22.toString());
System.out.println("-------------");
java.sql.Timestamp ts2 = java.sql.Timestamp.valueOf("2007-02-02 10:10:10");
System.out.println(getDateLabel(ts2, now));
System.out.println(ts2.toString());
System.out.println("-------------");
java.sql.Timestamp ts3 = java.sql.Timestamp.valueOf("2004-07-18 10:10:10");
System.out.println(getDateLabel(ts3, now));
System.out.println(ts3.toString());
System.out.println("-------------");
java.sql.Timestamp ts4 = java.sql.Timestamp.valueOf("2007-02-01 10:10:10");
System.out.println(getDateLabel(ts4, now));
System.out.println(ts4.toString());
System.out.println("-------------");
}
}
Today 2007-02-02 13:23:02.933 ------------- This Month 2007-01-06 09:01:10.0 ------------- Today 2007-02-02 10:10:10.0 ------------- Older 2004-07-18 10:10:10.0 ------------- Yesterday 2007-02-01 10:10:10.0 -------------
Get Date value from ResultSet
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getConnection();
Statement st = conn
.createStatement();
st.executeUpdate("create table survey (id int,myDate DATE );");
String INSERT_RECORD = "insert into survey(id, myDate) values(?, ?)";
PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);
pstmt.setString(1, "1");
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
pstmt.setDate(2, sqlDate);
pstmt.executeUpdate();
ResultSet rs = st.executeQuery("SELECT * FROM survey");
while (rs.next()) {
System.out.print(rs.getDate(2));
}
rs.close();
st.close();
conn.close();
}
private static Connection getConnection() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
String url = "jdbc:hsqldb:mem:data/tutorial";
return DriverManager.getConnection(url, "sa", "");
}
}
2007-02-02
Get the Current Date as a java.util.Date Object
The class java.util.Date represents a specific instant in time, with millisecond precision.
public class MainClass {
public static void main(String[] args) {
java.util.Date date = new java.util.Date();
}
}
Get the Current Timestamp as a java.sql.Time Object?
public class MainClass {
public static void main(String[] args) {
java.util.Date today = new java.util.Date();
System.out.println(new java.sql.Time(today.getTime()));
}
}
Get TIMESTAMP value from ResultSet
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getConnection();
Statement st = conn
.createStatement();
st.executeUpdate("create table survey (id int,myDate TIMESTAMP );");
String INSERT_RECORD = "insert into survey(id, myDate) values(?, ?)";
PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);
pstmt.setString(1, "1");
java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
pstmt.setTimestamp(2, sqlDate);
pstmt.executeUpdate();
ResultSet rs = st.executeQuery("SELECT * FROM survey");
while (rs.next()) {
System.out.print(rs.getTimestamp(2));
}
rs.close();
st.close();
conn.close();
}
private static Connection getConnection() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
String url = "jdbc:hsqldb:mem:data/tutorial";
return DriverManager.getConnection(url, "sa", "");
}
}
2007-02-02 12:46:40.632
Get TIME value from ResultSet
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getConnection();
Statement st = conn
.createStatement();
st.executeUpdate("create table survey (id int,myDate TIME );");
String INSERT_RECORD = "insert into survey(id, myDate) values(?, ?)";
PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);
pstmt.setString(1, "1");
java.sql.Time sqlDate = new java.sql.Time(new java.util.Date().getTime());
pstmt.setTime(2, sqlDate);
pstmt.executeUpdate();
ResultSet rs = st.executeQuery("SELECT * FROM survey");
while (rs.next()) {
System.out.print(rs.getTime(2));
}
rs.close();
st.close();
conn.close();
}
private static Connection getConnection() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
String url = "jdbc:hsqldb:mem:data/tutorial";
return DriverManager.getConnection(url, "sa", "");
}
}
12:47:21
Getting a Timestamp Object Using java.util.Date
public class MainClass {
public static void main(String[] args) {
java.util.Date today = new java.util.Date();
System.out.println(new java.sql.Timestamp(today.getTime()));
}
}
Getting a Timestamp Object Using System.currentTimeMillis()
public class MainClass {
public static void main(String[] args) {
new java.sql.Timestamp(System.currentTimeMillis());
}
}
Insert Date value
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getConnection();
Statement st = conn
.createStatement();
st.executeUpdate("create table survey (id int,myDate DATE);");
String INSERT_RECORD = "insert into survey(id, myDate) values(?, ?)";
PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);
pstmt.setString(1, "1");
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
pstmt.setDate(2, sqlDate);
pstmt.executeUpdate();
ResultSet rs = st.executeQuery("SELECT * FROM survey");
outputResultSet(rs);
rs.close();
st.close();
conn.close();
}
private static void outputResultSet(ResultSet rs) throws Exception {
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
for (int i = 1; i < numberOfColumns + 1; i++) {
String columnName = rsMetaData.getColumnName(i);
System.out.print(columnName + " ");
}
System.out.println();
System.out.println("----------------------");
while (rs.next()) {
for (int i = 1; i < numberOfColumns + 1; i++) {
System.out.print(rs.getString(i) + " ");
}
System.out.println();
}
}
private static Connection getConnection() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
String url = "jdbc:hsqldb:mem:data/tutorial";
return DriverManager.getConnection(url, "sa", "");
}
}
ID MYDATE ---------------------- 1 2007-02-02
Insert TIMESTAMP value
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getConnection();
Statement st = conn
.createStatement();
st.executeUpdate("create table survey (id int,myDate TIMESTAMP );");
String INSERT_RECORD = "insert into survey(id, myDate) values(?, ?)";
PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);
pstmt.setString(1, "1");
java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
pstmt.setTimestamp(2, sqlDate);
pstmt.executeUpdate();
ResultSet rs = st.executeQuery("SELECT * FROM survey");
outputResultSet(rs);
rs.close();
st.close();
conn.close();
}
private static void outputResultSet(ResultSet rs) throws Exception {
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
for (int i = 1; i < numberOfColumns + 1; i++) {
String columnName = rsMetaData.getColumnName(i);
System.out.print(columnName + " ");
}
System.out.println();
System.out.println("----------------------");
while (rs.next()) {
for (int i = 1; i < numberOfColumns + 1; i++) {
System.out.print(rs.getString(i) + " ");
}
System.out.println();
}
}
private static Connection getConnection() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
String url = "jdbc:hsqldb:mem:data/tutorial";
return DriverManager.getConnection(url, "sa", "");
}
}
ID MYDATE ---------------------- 1 2007-02-02 12:45:19.914000000
Insert TIME value
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getConnection();
Statement st = conn
.createStatement();
st.executeUpdate("create table survey (id int,myDate TIME);");
String INSERT_RECORD = "insert into survey(id, myDate) values(?, ?)";
PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);
pstmt.setString(1, "1");
java.sql.Time sqlDate = new java.sql.Time(new java.util.Date().getTime());
pstmt.setTime(2, sqlDate);
pstmt.executeUpdate();
ResultSet rs = st.executeQuery("SELECT * FROM survey");
outputResultSet(rs);
rs.close();
st.close();
conn.close();
}
private static void outputResultSet(ResultSet rs) throws Exception {
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
for (int i = 1; i < numberOfColumns + 1; i++) {
String columnName = rsMetaData.getColumnName(i);
System.out.print(columnName + " ");
}
System.out.println();
System.out.println("----------------------");
while (rs.next()) {
for (int i = 1; i < numberOfColumns + 1; i++) {
System.out.print(rs.getString(i) + " ");
}
System.out.println();
}
}
private static Connection getConnection() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
String url = "jdbc:hsqldb:mem:data/tutorial";
return DriverManager.getConnection(url, "sa", "");
}
}
ID MYDATE ---------------------- 1 12:44:14
Make a java.sql.Timestamp Object for a Given Year, Month, Day, Hour
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class MainClass {
public static void main(String[] a) {
System.out.println(makeTimestamp(2002,02,02,02,02,02,02));
}
public static Timestamp makeTimestamp(int year, int month, int day, int hour, int minute,
int second, int millisecond) {
Calendar cal = new GregorianCalendar();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DATE, day);
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, second);
cal.set(Calendar.MILLISECOND, millisecond);
// now convert GregorianCalendar object to Timestamp object
return new Timestamp(cal.getTimeInMillis());
}
}
2002-02-02 02:02:02.002
Returns a java.sql.Timestamp equal to the current time
public class Utils {
/**
* Returns a java.sql.Timestamp equal to the current time
**/
public static java.sql.Timestamp now() {
return new java.sql.Timestamp(new java.util.Date().getTime());
}
}
Working with Date, Time, and Timestamp in JDBC
The java.sql package provides the following classes that deal with date-related data types:
- java.sql.Date: Mapping for SQL DATE.
- java.sql.Time: Mapping for SQL TIME.
- java.sql.Timestamp: Mapping for SQL TIMESTAMP.