从 CalendarView 获取自 UNIX 纪元以来的 Millis 时间
Posted
技术标签:
【中文标题】从 CalendarView 获取自 UNIX 纪元以来的 Millis 时间【英文标题】:Getting time in Millis since UNIX epoch from a CalendarView 【发布时间】:2016-05-14 05:39:14 【问题描述】:我想找到当前时间和从日历视图中选择的日期之间的秒数。我目前的方法如下
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】: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());
);
【讨论】:
以上是关于从 CalendarView 获取自 UNIX 纪元以来的 Millis 时间的主要内容,如果未能解决你的问题,请参考以下文章
Microsoft Graph API calendarView 是不是仅限于一个月?如何获取所有事件?