JAVA,也常常用到時間,老是出錯,記錄一下:java
例如說,以這樣的形式從數據庫那邊拿到了消息:
/*
* Get System Date/Time
*/
pstmt = connection
.prepareStatement("SELECT TO_CHAR(sysdate,'YYYY-MM-DD HH24:MI:SS') FROM DUAL");
ResultSet rset1 = pstmt.executeQuery();數據庫
String datetime = "";
if (rset1.next()) {
datetime = rset1.getString(1);
}
if (pstmt != null)
pstmt.close();
if (rset1 != null)
rset1.close();函數
datetime 是這個形式的----》2014-05-22 15:39:20
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar FaultCalendar = null;
FaultCalendar=FaultCalendar.getInstance();
FaultCalendar.setTime(FalutDate);
Calendar nowCalendar=null;
nowCalendar=nowCalendar.getInstance();
System.out.println(datetime);
-------------------------------------------------------------------------------------------
因爲datetime 是這個形式的----》2014-05-22 15:39:20
轉換的話必須使用這種形式轉換,不然轉換不了,會出錯
Date dt=sdf1.parse(datetime);
nowCalendar.setTime(dt);
// 採用這種形式絕對錯誤: Date dt=new Date(datetime); 報錯爲:java.lang.IllegalArgumentException
-------------------------------------------------------------------------------------------
//getTimeInMillis() 這個函數能夠計算當前時間到一個固定時間點(from the epoch)的毫秒個數
long nowMillistTime=nowCalendar.getTimeInMillis();
long FaultMillisTime=FaultCalendar.getTimeInMillis();
long betweenMillistTime=nowMillistTime-FaultMillisTime;
betweenDay就是得出兩個時間點之間相差的天數。
int betweenDay=0;
if(betweenMillistTime<0) betweenDay=0;
else {
betweenDay=(int) (betweenMillistTime/(1000*3600*24));
}
int finalDay=PmMaxDuration-betweenDay-1;
//採用這種辦法,沒有對超過時限的作出應有的處理,可能會出現負值
orm