我想從TimeStamp中計算分鐘數。怎麼做?例如如何從java中的TimeStamp計算一分鐘?
我的TimeStamp值爲13/11/10 1:01 PM。我需要從現在開始幾分鐘內得到這些信息?
希望我清楚 感謝
我想從TimeStamp中計算分鐘數。怎麼做?例如如何從java中的TimeStamp計算一分鐘?
我的TimeStamp值爲13/11/10 1:01 PM。我需要從現在開始幾分鐘內得到這些信息?
希望我清楚 感謝
假設值是String
。
SimpleDateFormat
的parse()
方法getTime()
System.currentTimeMillis()
相差您Date
對象獲取長的時間和很長的getTime()
假設值在Timestamp
,跳過步驟1和步驟2.並注意s在時間s tamp是小寫字母。
Timestamp
是java.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,除非你有特殊的理由不使用它。
您可以使用Timestamp.getTime()
來獲取以毫秒爲單位的時間。 System.currentTimeMillis()
會在當前時間給你同樣的東西。減去它們併除以1000*60
以將毫秒轉換爲分鐘
我試過 long minutes = TimeUnit.MILLISECONDS.toMinutes(then - now); 但它給出了負值我把它改爲 long minutes = TimeUnit.MILLISECONDS.toMinutes(now - then); – 2016-10-27 11:39:10
@KhizarHayat:是的,如果'now'晚於'then',那將是正確的。 – 2016-10-27 13:09:14
Timestamp對於我來說是'java.sql.Timestamp' ...爲什麼不使用'getMinutes()',即使它已被棄用,而不是自己實現呢? – shinzou 2017-11-07 12:20:42