其實比較兩個時間的大小是很好弄的 date.before() date.after() 或者直接轉化爲毫秒數date.getTime() 再比較都行 ,但是對於不那麼精確的比較就不能這樣弄。
上午碰到一個問題:
判斷兩個時間是否在同一天
一個是當前時間currentDate 用已過時的Date方法 首設置currentDate.setHour(0);currentDate.setMinutes(0);currentDate.setSeconds(0) 。
一個是數據庫拿出來的時間sqlDate格式爲2013-01-06 00:00:00.0。
然後很傻很天真的用 if(currentDate.compareTo(sqlDate)==0){...} 結果沒有執行if裏面內容,DEBUG以後知道 比較的是毫秒數
然後用 if(sqlDate.getYear()==currentDate.getYear() &&sqlDate.getMonth()==currentDate.getMonth()&&sqlDate.getDay()==currentDate.getDay()){...}
然後執行了if裏面的內容 但是大家都知道Date.getYear(),Date.getMonth(),Date.getDay()都是已經過時的方法,是不建議使用的,但是我不瞭解到底會帶來什麼樣的隱患,通過查看源碼得知
/**
* Returns a value that is the result of subtracting 1900 from the
* year that contains or begins with the instant in time represented
* by this <code>Date</code> object, as interpreted in the local
* time zone.
*
* @return the year represented by this date, minus 1900.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.get(Calendar.YEAR) - 1900</code>.
*/
@Deprecated
public int getYear() {
return normalize().getYear() - 1900;
}
用這個方法獲取年份時是從1900年開始計算的,因此當年份爲2009時,得到的結果爲109,所以如果要得到最終的年份,要再加上1900。
而替代過時方法的方案如下:
Calendar calendar =Calendar.getInstance();
calendar.setTime(downTime);
calendar.get(Calendar.YEAR);
通過實驗得知拿到的就是當前的年份
最後的結論是 如果是兩個時間比較 上述兩種方法都可以,如果是和字符串比較就要小心了,最好是不要用過時的方法。
(ps:在網上找資料時候看到有人發帖說js裏用date,getYear()有時候拿不到正確的時間,他分析的原因是有的瀏覽器不支持,建議使用getFullYear(),有待驗證)