java 計算時間差,還剩下xx天xx小時xx分xx秒
阿新 • • 發佈:2019-02-14
計算時間差,還剩下xx天xx小時xx分xx秒
使用:
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
setDateInfo(milliseconds, textView);
handler.postDelayed(this, 1000);
}
};
runnable.run();
private void setDateInfo(long milliseconds, TextView textView) {
try {
Date currDate = new Date(System.currentTimeMillis());
Date endDate = new Date(milliseconds);
long diff = currDate.getTime() - endDate.getTime(); // 得到的差值是微秒級別,可以忽略
long days = diff / (1000 * 60 * 60 * 24);
long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
long seconds = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60) - minutes * (1000 * 60)) / (1000);
textView.setText("訂單將在"
+ ((2 - (days + 1)) < 0 ? "0" : (2 - (days + 1))) + "天"
+ (24 - (hours + 1)) + "小時"
+ (60 - (minutes + 1)) + "分"
+ (60 - (seconds + 1)) + "秒"
+ "自動關閉");
} catch (Exception e) {
e.printStackTrace();
}
}