下面列出了java.sql.Timestamp#setTime ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Return a new Timestamp object which value is adjusted according to known DATE, DATETIME or TIMESTAMP field precision.
*
* @param ts
* an original Timestamp object, not modified by this method
* @param fsp
* value in the range from 0 to 6 specifying fractional seconds precision
* @param serverRoundFracSecs
* Flag indicating whether rounding or truncation occurs on server when inserting a TIME, DATE, or TIMESTAMP value with a fractional seconds part
* into a column having the same type but fewer fractional digits: true means rounding, false means truncation. The proper value should be
* detected by analyzing sql_mode server variable for TIME_TRUNCATE_FRACTIONAL presence.
* @return A new Timestamp object cloned from original ones and then rounded or truncated according to required fsp value
*/
public static Timestamp adjustTimestampNanosPrecision(Timestamp ts, int fsp, boolean serverRoundFracSecs) {
if (fsp < 0 || fsp > 6) {
throw ExceptionFactory.createException(WrongArgumentException.class, "fsp value must be in 0 to 6 range.");
}
Timestamp res = (Timestamp) ts.clone();
int nanos = res.getNanos();
double tail = Math.pow(10, 9 - fsp);
if (serverRoundFracSecs) {
nanos = (int) Math.round(nanos / tail) * (int) tail;
if (nanos > 999999999) {
nanos %= 1000000000; // get only last 9 digits
res.setTime(res.getTime() + 1000); // increment seconds
}
} else {
nanos = (int) (nanos / tail) * (int) tail;
}
res.setNanos(nanos);
return res;
}
/**
* This method checks if customer end date is valid: 1. if a new address is being added, customer end date must be a future date
* 2. if inactivating an address, customer end date must be current or future date
*
* @param endDate
* @param canBeTodaysDateFlag
* @return True if endDate is valid.
*/
public boolean checkEndDateIsValid(Date endDate, boolean canBeTodaysDateFlag) {
boolean isValid = true;
if (ObjectUtils.isNull(endDate)) {
return isValid;
}
Timestamp today = dateTimeService.getCurrentTimestamp();
today.setTime(DateUtils.truncate(today, Calendar.DAY_OF_MONTH).getTime());
// end date must be todays date or future date
if (canBeTodaysDateFlag) {
if (endDate.before(today)) {
isValid = false;
}
} // end date must be a future date
else {
if (!endDate.after(today)) {
isValid = false;
}
}
return isValid;
}
@Override
public Timestamp copy(Timestamp from, Timestamp reuse) {
if (from == null) {
return null;
}
reuse.setTime(from.getTime());
reuse.setNanos(from.getNanos());
return reuse;
}
@Override
public Timestamp copy(Timestamp from, Timestamp reuse) {
if (from == null) {
return null;
}
reuse.setTime(from.getTime());
reuse.setNanos(from.getNanos());
return reuse;
}
@Override
public Timestamp deserialize(Timestamp reuse, DataInputView source) throws IOException {
final long v = source.readLong();
if (v == Long.MIN_VALUE) {
return null;
}
reuse.setTime(v);
reuse.setNanos(source.readInt());
return reuse;
}
@Test
public void test36() {
Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
Timestamp ts2 = Timestamp.valueOf("1961-08-30 00:00:00");
ts2.setTime(ts1.getTime());
assertTrue(ts2.getTime() == ts1.getTime(),
"ts1.getTime() != ts2.getTime()");
assertTrue(ts1.equals(ts2), "Error ts1 != ts2");
}
@Test
public void test36() {
Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
Timestamp ts2 = Timestamp.valueOf("1961-08-30 00:00:00");
ts2.setTime(ts1.getTime());
assertTrue(ts2.getTime() == ts1.getTime(),
"ts1.getTime() != ts2.getTime()");
assertTrue(ts1.equals(ts2), "Error ts1 != ts2");
}
@Override
public Timestamp copy(Timestamp from, Timestamp reuse) {
if (from == null) {
return null;
}
reuse.setTime(from.getTime());
reuse.setNanos(from.getNanos());
return reuse;
}
@Override
public Timestamp copy(Timestamp from, Timestamp reuse) {
if (from == null) {
return null;
}
reuse.setTime(from.getTime());
reuse.setNanos(from.getNanos());
return reuse;
}
@Test
public void test36() {
Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
Timestamp ts2 = Timestamp.valueOf("1961-08-30 00:00:00");
ts2.setTime(ts1.getTime());
assertTrue(ts2.getTime() == ts1.getTime(),
"ts1.getTime() != ts2.getTime()");
assertTrue(ts1.equals(ts2), "Error ts1 != ts2");
}
@Test
public void test36() {
Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
Timestamp ts2 = Timestamp.valueOf("1961-08-30 00:00:00");
ts2.setTime(ts1.getTime());
assertTrue(ts2.getTime() == ts1.getTime(),
"ts1.getTime() != ts2.getTime()");
assertTrue(ts1.equals(ts2), "Error ts1 != ts2");
}
@Test
public void test36() {
Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
Timestamp ts2 = Timestamp.valueOf("1961-08-30 00:00:00");
ts2.setTime(ts1.getTime());
assertTrue(ts2.getTime() == ts1.getTime(),
"ts1.getTime() != ts2.getTime()");
assertTrue(ts1.equals(ts2), "Error ts1 != ts2");
}
@Test
public void test36() {
Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
Timestamp ts2 = Timestamp.valueOf("1961-08-30 00:00:00");
ts2.setTime(ts1.getTime());
assertTrue(ts2.getTime() == ts1.getTime(),
"ts1.getTime() != ts2.getTime()");
assertTrue(ts1.equals(ts2), "Error ts1 != ts2");
}
@Test
public void test36() {
Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
Timestamp ts2 = Timestamp.valueOf("1961-08-30 00:00:00");
ts2.setTime(ts1.getTime());
assertTrue(ts2.getTime() == ts1.getTime(),
"ts1.getTime() != ts2.getTime()");
assertTrue(ts1.equals(ts2), "Error ts1 != ts2");
}
public static void convertTimeToLocalTimeZone(TimeZone fromTimeZone, Timestamp timestamp)
{
if (timestamp == null) return;
int offset = getOffsetFromTimeZoneToDefault(fromTimeZone, timestamp);
if (offset != 0)
{
int nanos = timestamp.getNanos();
timestamp.setTime(timestamp.getTime() + offset);
timestamp.setNanos(nanos);
}
}
/**
* 根据readerID获取当前借阅书籍,分页显示
*
* @author zengyaoNPU
* @param start
* 起始行
* @param count
* 每页行数
* @param readerId
* @return BorrowItem列表
*/
public List<BorrowItem> getBorrowItemInCurrent(int start, int count, int readerId) {
Connection conn = null;
Statement st = null;
ResultSet rs;
List<BorrowItem> list = new ArrayList<BorrowItem>();
try {
conn = DatabaseUtil.getInstance().getConnection();
st = conn.createStatement();
String sql = "SELECT reader.reader_id,reader.`reader_name`," + "book.isbn,book.book_name,"
+ "book_in_library.book_id,book_in_library.`state`,"
+ "borrow_item.`borrow_time`,borrow_item.`return_time`,borrow_item.`borrow_id`,borrow_item.`borrow_librarian_id`,"
+ "librarian.`librarian_name` " + "FROM book,reader,book_in_library,borrow_item,librarian "
+ "WHERE borrow_item.`reader_id`=reader.`reader_id`"
+ "AND book_in_library.`book_id`=borrow_item.`book_id`" + "AND book.isbn=book_in_library.`isbn`"
+ "AND librarian.`librarian_id`=borrow_item.`borrow_librarian_id`" + "AND return_time IS NULL "
+ "AND reader.reader_id=" + readerId + " " + "LIMIT " + start + "," + count;
rs = st.executeQuery(sql);
while (rs.next()) {
// 获取参数
int borrowId = rs.getInt("borrow_id");
int bookId = rs.getInt("book_id");
String bookName = rs.getString("book_name");
int borrowLibrarianId = rs.getInt("borrow_librarian_id");
String state = rs.getString("state");
Timestamp borrowTime = rs.getTimestamp("borrow_time");
Timestamp returnTime = rs.getTimestamp("borrow_time");
returnTime.setTime(returnTime.getTime() + 1000 * 60 * 60 * 24 * 15);
returnTime.setTime(returnTime.getTime() + 1000 * 60 * 60 * 24 * 15);
String readerName = rs.getString("reader_name");
String borrowLibrarianName = rs.getString("librarian_name");
// 实例化
BorrowItem borrowItem = new BorrowItem();
borrowItem.setBookId(bookId);
borrowItem.setBookName(bookName);
borrowItem.setBorrowId(borrowId);
borrowItem.setBorrowLibrarianId(borrowLibrarianId);
borrowItem.setReaderId(readerId);
borrowItem.setBorrowTime(borrowTime);
borrowItem.setReturnTime(returnTime);
borrowItem.setState(state);
borrowItem.setReaderName(readerName);
borrowItem.setBorrowLibrarianName(borrowLibrarianName);
// 加入列表
list.add(borrowItem);
}
return list;
} catch (Exception e) {
System.out.println(
"--BorrowItemDAO--,--getBorrowItemInCurrent(int start,int count,int readerId)--,suffers exception");
return null;
}
}
/**
* 获取当前借阅,根据读者ID,不分页显示
*
* @author zengyaoNPU
* @param readerId
* @return 列表
*/
public List<BorrowItem> getBorrowItemInCurrent(int readerId) {
Connection conn = null;
Statement st = null;
ResultSet rs;
List<BorrowItem> list = new ArrayList<BorrowItem>();
try {
conn = DatabaseUtil.getInstance().getConnection();
st = conn.createStatement();
String sql = "SELECT reader.reader_id,reader.`reader_name`," + "book.isbn,book.book_name,"
+ "book_in_library.book_id,book_in_library.`state`,"
+ "borrow_item.`borrow_time`,borrow_item.`return_time`,borrow_item.`borrow_id`,borrow_item.`borrow_librarian_id`,"
+ "librarian.`librarian_name` " + "FROM book,reader,book_in_library,borrow_item,librarian "
+ "WHERE borrow_item.`reader_id`=reader.`reader_id`"
+ "AND book_in_library.`book_id`=borrow_item.`book_id`" + "AND book.isbn=book_in_library.`isbn`"
+ "AND librarian.`librarian_id`=borrow_item.`borrow_librarian_id`" + "AND return_time IS NULL "
+ "AND reader.reader_id=" + readerId;
rs = st.executeQuery(sql);
while (rs.next()) {
// 获取参数
int borrowId = rs.getInt("borrow_id");
int bookId = rs.getInt("book_id");
String bookName = rs.getString("book_name");
int borrowLibrarianId = rs.getInt("borrow_librarian_id");
String state = rs.getString("state");
Timestamp borrowTime = rs.getTimestamp("borrow_time");
Timestamp returnTime = rs.getTimestamp("borrow_time");
returnTime.setTime(returnTime.getTime() + 1000 * 60 * 60 * 24 * 15);
returnTime.setTime(returnTime.getTime() + 1000 * 60 * 60 * 24 * 15);
String readerName = rs.getString("reader_name");
String borrowLibrarianName = rs.getString("librarian_name");
// 实例化
BorrowItem borrowItem = new BorrowItem();
borrowItem.setBookId(bookId);
borrowItem.setBookName(bookName);
borrowItem.setBorrowId(borrowId);
borrowItem.setBorrowLibrarianId(borrowLibrarianId);
borrowItem.setReaderId(readerId);
borrowItem.setBorrowTime(borrowTime);
borrowItem.setReturnTime(returnTime);
borrowItem.setState(state);
borrowItem.setReaderName(readerName);
borrowItem.setBorrowLibrarianName(borrowLibrarianName);
// 加入列表
list.add(borrowItem);
}
return list;
} catch (Exception e) {
System.out.println("--BorrowItemDAO--,--getBorrowItemInCurrent(int readerId)--,suffers exception");
return null;
}
}
public static synchronized void add_one_row(Connection conn, int thread_id)
throws Exception {
try {
//initialize();
PreparedStatement ps = conn.prepareStatement(
" insert into Datatypes (id,t_char,t_blob," + "t_clob,"
+ " t_date, t_decimal, t_decimal_nn, t_double, "
+ " t_float, t_int, t_longint, t_numeric_large,"
+ " t_real, t_smallint, t_time, t_timestamp,"
+ " t_varchar) values ("
+ " ?,?, ?,?, ?, ?,?, ?, ?, ?,?, ?, ?, ?, ?, ?,?)"
/* autoincrement feature added, so we need to specify the
* column name for prepared statement, otherwise auto increment
* column will think it is trying to update/insert a null value
* to the column.
*/
, Statement.RETURN_GENERATED_KEYS);
InputStream streamIn = null;
Reader streamReader = null;
int ind = Rn.nextInt();
double x;
Date dt = new Date(1);
Time tt = new Time(1);
Timestamp ts = new Timestamp(1);
String cs = "asdf qwerqwer 12341234 ZXCVZXCVZXCV [email protected]#[email protected]#$ asdfasdf 1 q a z asdf ASDF qwerasdfzxcvasdfqwer1234asd#";
ps.setInt(1, ind);
// scramble the string
int i1 = Math.abs(ind % 100);
String cs2 = cs.substring(i1, 99) + cs.substring(0, i1);
int i2 = i1 < 89 ? i1 + 10 : i1;
ps.setString(2, cs2.substring(0, i2));
//"t_blob"
int blobLength = Rn.nextInt(102400 - 0 + 1) + 0;//to create a stream of random length between 0 and 100K
streamIn = new LoopingAlphabetStream(blobLength);
ps.setBinaryStream(3, streamIn, blobLength);
//"t_clob
int clobLength = Rn.nextInt(102400 - 0 + 1) + 0;//to create a stream of random length between 0 and 100K
streamReader = new LoopingAlphabetReader(clobLength, CharAlphabet
.modernLatinLowercase());
ps.setCharacterStream(4, streamReader, clobLength);
//"t_ndate"
dt.setTime(Math.abs(Rn.nextLong() / 150000));
ps.setDate(5, dt);
//"t_decimal"
x = Math.abs(Rn.nextInt() % 18);
if (x > 5)
x = 5;
ps.setDouble(6, Math.abs(Rn.nextDouble() * Math.pow(10, x)));
//"t_decimal_nn"
ps.setDouble(7, Rn.nextDouble());
//"t_double"
ps.setDouble(8, Rn.nextDouble()
* Math.pow(10, Math.abs(Rn.nextInt() % 300)));
//"t_float"
ps.setFloat(9, Rn.nextFloat()
* (float) Math.pow(10, Math.abs(Rn.nextInt() % 30)));
//"t_int"
ps.setInt(10, Rn.nextInt());
//"t_longint"
ps.setLong(11, Rn.nextLong());
//"t_numeric_large"
x = Math.abs(Rn.nextInt() % 30);
if (x > 30)
x = 31;
ps.setDouble(12, Math.abs(Rn.nextDouble() * Math.pow(10, x)));
//"t_real"
ps.setFloat(13, Rn.nextFloat()
* (float) Math.pow(10, Math.abs(Rn.nextInt() % 7)));
//"t_smallint"
ps.setInt(14, Rn.nextInt() % (256 * 128));
//"t_time"
tt.setTime(Math.abs(Rn.nextInt()));
ps.setTime(15, tt);
//"t_timestamp"
ts.setTime(Math.abs(Rn.nextLong() / 50000));
ps.setTimestamp(16, ts);
//"t_varchar"
ps.setString(17, cs.substring(Math.abs(Rn.nextInt() % 100)));
int rows = ps.executeUpdate();
if (rows == 1) {
ResultSet rs = ps.getGeneratedKeys();
while (rs.next()) {
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
}
} else
System.out.println("t" + thread_id + " insert failed");
streamReader.close();
streamIn.close();
} catch (SQLException se) {
if (se.getNextException() == null)
throw se;
String m = se.getNextException().getSQLState();
System.out.println(se.getNextException().getMessage()
+ " SQLSTATE: " + m);
}
}
private void initMaxSizes2(){
dateSize = 0;
timeSize = 0;
timestampSize = 0;
int len;
// check the date & timestamp max length
// 3900/01/28 !! original devloper thought they were getting 2000/01/28
Date d = new Date(60907276800000L);
Timestamp t = new Timestamp(d.getTime());
for(int month = 0 ; month <=11 ; month++, d.setTime(d.getTime() + (30L * 24L * 60L * 60L * 1000L))) {
len=getDateAsString(d).length();
if(len > dateSize ) {
dateSize=len;
}
t.setTime(d.getTime() + ((((21L * 60L) + 59L) * 60L) + 59L));
len=getTimestampAsString(t).length();
if(len > timestampSize) {
timestampSize=len;
}
}
// set the time max length
// minimum of 18 because the old buggy code always used 18
len = 18;
for (int hour = 0 ; hour < 24; hour++) {
long secs = (hour * 3600L) + (59 * 60L) + 59L;
long ms = secs * 1000L;
Date td = new Date(ms);
String fd = formatTime.format(td);
if (fd.length() > len)
len = fd.length();
}
timeSize=len;
}
public static synchronized void add_one_row(Connection conn, int thread_id)
throws Exception {
try {
//initialize();
PreparedStatement ps = conn.prepareStatement(
" insert into Datatypes (id,t_char,t_blob," + "t_clob,"
+ " t_date, t_decimal, t_decimal_nn, t_double, "
+ " t_float, t_int, t_longint, t_numeric_large,"
+ " t_real, t_smallint, t_time, t_timestamp,"
+ " t_varchar) values ("
+ " ?,?, ?,?, ?, ?,?, ?, ?, ?,?, ?, ?, ?, ?, ?,?)"
/* autoincrement feature added, so we need to specify the
* column name for prepared statement, otherwise auto increment
* column will think it is trying to update/insert a null value
* to the column.
*/
, Statement.RETURN_GENERATED_KEYS);
InputStream streamIn = null;
Reader streamReader = null;
int ind = Rn.nextInt();
double x;
Date dt = new Date(1);
Time tt = new Time(1);
Timestamp ts = new Timestamp(1);
String cs = "asdf qwerqwer 12341234 ZXCVZXCVZXCV [email protected]#[email protected]#$ asdfasdf 1 q a z asdf ASDF qwerasdfzxcvasdfqwer1234asd#";
ps.setInt(1, ind);
// scramble the string
int i1 = Math.abs(ind % 100);
String cs2 = cs.substring(i1, 99) + cs.substring(0, i1);
int i2 = i1 < 89 ? i1 + 10 : i1;
ps.setString(2, cs2.substring(0, i2));
//"t_blob"
int blobLength = Rn.nextInt(102400 - 0 + 1) + 0;//to create a stream of random length between 0 and 100K
streamIn = new LoopingAlphabetStream(blobLength);
ps.setBinaryStream(3, streamIn, blobLength);
//"t_clob
int clobLength = Rn.nextInt(102400 - 0 + 1) + 0;//to create a stream of random length between 0 and 100K
streamReader = new LoopingAlphabetReader(clobLength, CharAlphabet
.modernLatinLowercase());
ps.setCharacterStream(4, streamReader, clobLength);
//"t_ndate"
dt.setTime(Math.abs(Rn.nextLong() / 150000));
ps.setDate(5, dt);
//"t_decimal"
x = Math.abs(Rn.nextInt() % 18);
if (x > 5)
x = 5;
ps.setDouble(6, Math.abs(Rn.nextDouble() * Math.pow(10, x)));
//"t_decimal_nn"
ps.setDouble(7, Rn.nextDouble());
//"t_double"
ps.setDouble(8, Rn.nextDouble()
* Math.pow(10, Math.abs(Rn.nextInt() % 300)));
//"t_float"
ps.setFloat(9, Rn.nextFloat()
* (float) Math.pow(10, Math.abs(Rn.nextInt() % 30)));
//"t_int"
ps.setInt(10, Rn.nextInt());
//"t_longint"
ps.setLong(11, Rn.nextLong());
//"t_numeric_large"
x = Math.abs(Rn.nextInt() % 30);
if (x > 30)
x = 31;
ps.setDouble(12, Math.abs(Rn.nextDouble() * Math.pow(10, x)));
//"t_real"
ps.setFloat(13, Rn.nextFloat()
* (float) Math.pow(10, Math.abs(Rn.nextInt() % 7)));
//"t_smallint"
ps.setInt(14, Rn.nextInt() % (256 * 128));
//"t_time"
tt.setTime(Math.abs(Rn.nextInt()));
ps.setTime(15, tt);
//"t_timestamp"
ts.setTime(Math.abs(Rn.nextLong() / 50000));
ps.setTimestamp(16, ts);
//"t_varchar"
ps.setString(17, cs.substring(Math.abs(Rn.nextInt() % 100)));
int rows = ps.executeUpdate();
if (rows == 1) {
ResultSet rs = ps.getGeneratedKeys();
while (rs.next()) {
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
}
} else
System.out.println("t" + thread_id + " insert failed");
streamReader.close();
streamIn.close();
} catch (SQLException se) {
if (se.getNextException() == null)
throw se;
String m = se.getNextException().getSQLState();
System.out.println(se.getNextException().getMessage()
+ " SQLSTATE: " + m);
}
}