1

現在、ユーザーが日付を入力できる機能をアプリに組み込み、それを保存するときに、今日からその日付までの残り日数を計算したいと考えています。私のコードは以下の通りです:

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

このコードを実行して、2015 年 7 月 19 日の日付を入力すると、残りの日数は 760 として返され、730 になるはずでした。計算が少しずれていると思います。

ありがとう

4

2 に答える 2

1

エラーは月の計算にあります。Java では、月は 0 ベース (0 は 1 月) です。

したがって、

int mMonth = Integer.parseInt(ar[0]);

あなたの例のように正しくありません.8月と解釈されます.

1 を引く必要があります:

int mMonth = Integer.parseInt(ar[0]) - 1;

編集 - 詳細

TimerSet.set(0, 5, 0, mDay, mMonth, mYear);

0 ベースで 1 か月かかります。あなたの例では、7 は 8 月として理解されるため、解析した 1 ベースの値から 1 を引く必要があります。

于 2013-07-19T14:14:17.643 に答える