亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何計算當前系統時間和存儲時間間隔

如何計算當前系統時間和存儲時間間隔

四季花海 2023-03-09 15:18:12
我想計算當前系統時間和存儲時間間隔。我在我的應用程序中使用 admob。當用戶點擊我要存儲當前時間的廣告時sharedPreferences,下一個廣告應在 10 分鐘后顯示。sharedPreferences那么我如何計算存儲時間和當前系統時間之間的間隔呢?這是我的代碼。 interstitialAd.setAdListener(new AdListener() {     @Override     public void onAdClosed() {         super.onAdClosed();         startActivity(intent);         interstitialAd.loadAd(new AdRequest.Builder().build());     }     @Override     public void onAdLoaded() {         // Code to be executed when an ad finishes loading.         Toast.makeText(Chapters.this, "loaded", Toast.LENGTH_SHORT).show();     }     @Override     public void onAdFailedToLoad(int errorCode) {         // Code to be executed when an ad request fails.     }     @Override     public void onAdOpened() {         // Code to be executed when the ad is displayed.     }     @Override     public void onAdClicked() {         SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");         // Find todays date         String currentDateTime = dateFormat.format(new Date());          sharedPreferences=getSharedPreferences("TimeStamp",MODE_PRIVATE);         SharedPreferences.Editor editor=sharedPreferences.edit();         editor.putString("currenttime",currentDateTime);         editor.commit();     }     @Override     public void onAdLeftApplication() {         // Code to be executed when the user has left the app.     }}
查看完整描述

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 ) ;


查看完整回答
反對 回復 2023-03-09
  • 1 回答
  • 0 關注
  • 99 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號