1 回答

TA貢獻1943條經驗 獲得超7個贊
您正在使用多年前被 JSR 310 中定義的現代java.time類所取代的可怕的日期時間類。
來自問題:
當用戶點擊廣告時,我想將當前時間存儲在 sharedPreferences 中
將UTC中的當前時刻捕獲為Instant對象。
Instant instant = Instant.now() ;
生成標準ISO 8601格式的字符串。
String output = instant.toString() ;
2019-07-06T04:21:11.091261Z
為簡單起見,您可能希望將小數秒降為零。
Instant instant = Instant.now().truncatedTo( ChronoUnit.SECONDS ) ;
將此字符串寫入存儲。
來自問題:
計算存儲在 sharedPreferences 中的時間與當前系統時間之間的間隔?
檢索存儲的字符串。解析為Instant對象。
Instant instant = Instant.parse( input ) ;
使用Duration類計算經過的時間。
Duration d = Duration.between( instant , Instant.now() ) ;
完整性檢查。
Boolean movingForwardInTime = ( ! d.isNegative() ) && ( ! d.isZero() ) ;
if ( ! movingForwardInTime ) { … }
測試是否超過我們的限制。
Duration limit = Duration.ofMinutes( 10 ) ;
Boolean expired = ( d.compareTo( limit ) > 0 ) ;
添加回答
舉報