2010-11-12 46 views

回答

4

假設值是String

  1. 解析使用SimpleDateFormatparse()方法
  2. 使用getTime()
  3. System.currentTimeMillis()相差您Date對象獲取長的時間和很長的getTime()
  4. 分水嶺收到1000該字符串然後60

假設值在Timestamp ,跳過步驟1和步驟2.並注意s在時間s tamp是小寫字母。

5

Timestampjava.util.Date與更多的精度 - 所以假設你沒有太在意毫微秒,只需要調用它getTime()得到米利斯從紀元:

long now = System.currentTimeMillis(); // See note below 
long then = timestamp.getTime(); 

// Positive if 'now' is later than 'then', 
// negative if 'then' is later than 'now' 
long minutes = TimeUnit.MILLISECONDS.toMinutes(now - then); 

注意,對於可測性,我個人不會使用System.currentTimeMillis - 我會有一個接口(例如Clock)代表「當前時間服務」,並注入。你可以很容易地有一個假時鐘。

編輯:我假設你已經有了一個解析值。如果你沒有,只有一個字符串,你需要先解析它。我個人建議Joda Time作爲一個比內置的東西更好的日期和時間API,除非你有特殊的理由不使用它。

+0

我試過 long minutes = TimeUnit.MILLISECONDS.toMinutes(then - now); 但它給出了負值我把它改爲 long minutes = TimeUnit.MILLISECONDS.toMinutes(now - then); – 2016-10-27 11:39:10

+1

@KhizarHayat:是的,如果'now'晚於'then',那將是正確的。 – 2016-10-27 13:09:14

+0

Timestamp對於我來說是'java.sql.Timestamp' ...爲什麼不使用'getMinutes()',即使它已被棄用,而不是自己實現呢? – shinzou 2017-11-07 12:20:42