我目前正在尝试在我的应用程序中加入一个用户可以输入日期的功能,然后当他们保存它时,我想计算从今天到该日期还剩多少天。我的代码如下:
public void daysLeft(String dateSent){
String []ar = dateSent.split("[/]");
int mDay = Integer.parseInt(ar[1]);
int mMonth = Integer.parseInt(ar[0]);
int mYear = Integer.parseInt(ar[2]);
Time TimerSet = new Time();
TimerSet.set(0, 5, 0, mDay, mMonth, mYear); //day month year
TimerSet.normalize(true);
long millis = TimerSet.toMillis(true);
Time TimeNow = new Time();
TimeNow.setToNow(); // set the date to Current Time
TimeNow.normalize(true);
long millis2 = TimeNow.toMillis(true);
long millisset = millis - millis2; //subtract current from future to set the time remaining
final int smillis = (int) (millis); //convert long to integer to display conversion results
final int smillis2 = (int) (millis2);
new CountDownTimer(millisset, 1000) {
public void onTick(long millisUntilFinished) {
mText = (TextView)findViewById(R.id.DateData);
// decompose difference into days, hours, minutes and seconds
int weeks = (int) ((millisUntilFinished / 1000) / 604800);
int days = (int) ((millisUntilFinished / 1000) / 86400);
int hours = (int) (((millisUntilFinished / 1000) - (days * 86400)) / 3600);
int minutes = (int) (((millisUntilFinished / 1000)
- ((days * 86400) + (hours * 3600))) / 60);
int seconds = (int) ((millisUntilFinished / 1000) % 60);
int millicn = (int) (millisUntilFinished / 1000);
mText.setText(" " + days);
saveDate(String.valueOf(days));
}
public void onFinish() {}
}.start();
}
当我运行此代码并输入日期 19/07/2015 时,剩余的天数会返回 760 天,它们应该是 730 天。我认为有一些计算略有偏差,非常感谢您对此的帮助。
谢谢