【发布时间】:2015-03-06 11:18:52
【问题描述】:
所以我正在编写一个与闹钟功能相似的应用程序。它要求用户输入时间。但我一直在思考如何解决这个问题。
该方法需要找到用户选择的时间和当前时间之间的分钟差。假设用户将始终输入当前时间之后的时间(否则使用我的应用程序没有意义),差异将只是(userTimeInMins - currTimeInMins),其中两者都由((小时* 60) + 分钟)。
但是。这就是问题所在:
Ex 1) 如果当前时间是晚上 10 点,并且用户输入时间是凌晨 2 点。上面的算法会说这两个时间之间的差异是 (22 * 60 + 0) - (2 * 60 + 0),这显然是不正确的,因为这意味着晚上 10 点和凌晨 2 点之间有 20 小时的差异,当差异实际上是4小时。
例 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.
};
感谢您提前提供的任何帮助。
【问题讨论】:
-
为什么不使用
Date对象?这样会更简单 -
@AnthonyRaymond 并结合使用 datepicker 和 timepicker?在这种情况下,我将如何找到分钟的差异?我觉得它会同样复杂。
标签: java android time logic timepicker