从CalendarView获取UNIX纪元以来的Millis时间

时间:2016-02-04 14:39:07

标签: java android android-studio epoch

我想找到当前时间和从日历视图中选择的日期之间的秒数。我目前的方法如下

    mCalculateButton = (Button) findViewById(R.id.calcButton);
    mDatePicker = (CalendarView) findViewById(R.id.calendarView);

    mCalculateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //Grabbing the date selected from the CalendarView to send to intent
            long age = mDatePicker.getDate();
            startCalculation(age);

        }
    });
}

private void startCalculation(long age){
    Intent intent = new Intent(this, CalcActivity.class);
    intent.putExtra("key_age", age);
    startActivity(intent);
}

并在计算活动中

    Intent intent = getIntent();

    //Date selected in MSUE
    mSelectedTime = intent.getLongExtra("key_age", 0);

    //Current date in MSUE
    mCurrTime = System.currentTimeMillis();

    mSecondsInfo = (TextView) findViewById(R.id.secondsInfo);
    mDaysInfo = (TextView) findViewById(R.id.daysInfo);
    mMonthsInfo = (TextView) findViewById(R.id.monthsInfo);
    mYearsInfo = (TextView) findViewById(R.id.yearsInfo);

    //Replacing format specifiers with desired age information
    mSecondsInfo.setText(mSecondsInfo.getText().toString().replace("%i%", Long.toString(ageInSeconds(mSelectedTime, mCurrTime))));
    mDaysInfo.setText(mDaysInfo.getText().toString().replace("%i%", Long.toString(ageInDays(mSelectedTime, mCurrTime))));
    mMonthsInfo.setText(mMonthsInfo.getText().toString().replace("%i%", Long.toString(ageInMonths(mSelectedTime, mCurrTime))));
    mYearsInfo.setText(mYearsInfo.getText().toString().replace("%i%", Long.toString(ageInYears(mSelectedTime, mCurrTime))));
}

private long ageInSeconds(long mil, long currTime){
    return (currTime - mil) / 1000;
}
private long ageInDays(long mil, long currTime){
    return (currTime - mil)/ 1000 / 60 / 60 / 24;
}
private long ageInMonths(long mil, long currTime){
    return (currTime - mil) / 1000 / 60 / 60 / 24/ 30;
}
private long ageInYears(long mil, long currTime){
    return  (currTime - mil) / 1000 / 60 / 60 / 24/ 30 / 12;
}

问题是mDatePicker.getDate返回的时间每天增加约4000毫秒,它增加,我不明白为什么。关于为什么这不起作用的任何想法?

1 个答案:

答案 0 :(得分:1)

CalendarView不存储所选日期,但您可以收听选择事件并自行存储。

mDatePicker .setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
        @Override
        public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
             storedDate = new GregorianCalendar(year,month,dayOfMonth);
        }
    });

mCalculateButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        startCalculation(storedDate.getTimeInMillis());
    }
});