所以我正在编写一个具有与闹钟类似功能的应用程序。它要求用户输入时间。但有一段时间我一直在思考如何解决这个问题。
该方法需要找出用户选择的时间与当前时间之间的分钟差。假设用户总是输入当前时间之后的时间(否则使用我的应用程序就没有意义),差异就是 (userTimeInMins - currTimeInMins),两者都是通过 ((小时 * 60) + 分钟) 计算的。
但是。问题是这样的:
Ex 1) 如果当前时间为晚上 10 点,并且用户输入时间为凌晨 2 点。上面的算法会说两个时间之间的差异是 (22 * 60 + 0) - (2 * 60 + 0),这显然是不正确的,因为这意味着晚上 10 点和凌晨 2 点之间存在 20 小时的差异,而实际上差异是 4 小时。
Ex 2) 如果当前时间为下午 1 点,用户输入时间为凌晨 2 点。上面的算法会说两个时间之间的差异是 (13 * 60 + 0) - (2 * 60 + 0),这又是不正确的,因为这意味着存在 11 小时的差异,而实际上差异是 13 小时。
到目前为止我所拥有的
我意识到,对于示例 1 和示例 2,分钟差异可以通过以下方式计算 (((24 + userHours) * 60) + userMinutes) - currTimeInMins
我正在努力想出方法中的决策语句来确定是使用第一种方法还是第二种方法来计算以分钟为单位的差异。
代码
// Listener for the time selection
TimePickerDialog.OnTimeSetListener time = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String currAM_PM = "";
String userAM_PM = "";
// Get user AM/PM
int hourToShow = 0;
if (hourOfDay > 12){
hourToShow = hourOfDay - 12;
userAM_PM = "PM"
}
else if (hourOfDay == 12){
hourToShow = hourOfDay;
userAM_PM = "PM"
}
else{
hourToShow = hourOfDay;
userAM_PM = "AM"
}
// Update the time field to show the selected time in 12-hr format
EditText timeField = (EditText) findViewById(R.id.editTime);
timeField.setText(hourToShow + ":" + minute + " " + userAM_PM);
// Get current hour
SimpleDateFormat sdf = new SimpleDateFormat("HH");
String cHour = sdf.format(new Date());
int currHour = Integer.parseInt(cHour);
// Get current AM/PM
if (currHour > 12){
currAM_PM = "PM"
}
else if (currHour == 12){
currAM_PM = "PM"
}
else{
currAM_PM = "AM"
}
// Calculate the time to use
// If the selected hour is less than the current hour AND am_pm is "AM"
// THIS IS THE WHERE I NEED HELP
//--------------------------------------------------------------
if(currAM_PM == "PM" && userAM_PM == "AM" .... ??????) {
//take 24, add the hour, use same minute. so that 3 am is 27:00.
timeToUse = ((24 + hourOfDay) * 60) + minute;
}
else
timeToUse = (hourOfDay * 60) + minute;
}
// timeToUse is then passed through an intent extra to the next activity
// where the difference between it and the current time is calculated and used
// for other purposes.
};
感谢您提前提供的任何帮助。
最佳答案
解决方案
我使用 DatePickerDialog 和 TimePickerDialog 来加载带有用户选择的年份、月份等的日历对象。
然后我创建了一个 Date 对象,将其初始化为 cal.getDate()。
然后,我将 Date.getDate() 加载到一个 long 变量中,给出 1970 年 1 月 1 日以来的时间(以毫秒为单位)。
然后我将此数字除以 60000 以获得以分钟为单位的时间。
我对当前日期做了同样的事情,并发现了两者之间的差异。 感谢您的帮助。
关于java - 查找某个时间与当前时间之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27838495/