Android开发:如何计算TimePicker选中时间与当前时间的差值
Calculate Time Difference Between TimePicker Selection and Current Time
Hey there! Let's get that time difference calculation working for you. First, a quick note: your original code grabs the current time only when the activity starts, which will be outdated if the user waits to select a time. We'll fix that and add the difference logic step by step.
Here's the revised code with full time difference functionality:
public class ScheduleMessage extends AppCompatActivity { TextView textView; TimePicker timePicker; String date, timeDifference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_schedule_message); timePicker = findViewById(R.id.simpleTimePicker); textView = findViewById(R.id.selectedTime); timePicker.setOnTimeChangedListener( new TimePicker.OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { // 1. Get fresh current time when the user selects a time Calendar currentCalendar = Calendar.getInstance(); long currentTimeMillis = currentCalendar.getTimeInMillis(); // 2. Create a Calendar for the selected time (same date as current) Calendar selectedCalendar = Calendar.getInstance(); selectedCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay); selectedCalendar.set(Calendar.MINUTE, minute); selectedCalendar.set(Calendar.SECOND, 0); // Standardize seconds to 0 selectedCalendar.set(Calendar.MILLISECOND, 0); long selectedTimeMillis = selectedCalendar.getTimeInMillis(); // 3. Calculate the raw difference in milliseconds long differenceMillis = selectedTimeMillis - currentTimeMillis; // 4. Convert milliseconds to hours and minutes for readability long hours = differenceMillis / (1000 * 60 * 60); long minutes = (differenceMillis % (1000 * 60 * 60)) / (1000 * 60); // Format the selected time string date = String.format("%02d:%02d", hourOfDay, minute); // Handle negative differences (selected time is earlier in the day) timeDifference = String.format("%s%02d hours %02d minutes", differenceMillis < 0 ? "-" : "", Math.abs(hours), Math.abs(minutes)); // Update the TextView with all details textView.setText(String.format("Selected: %s | Current: %s | Difference: %s", date, new SimpleDateFormat("HH:mm").format(currentCalendar.getTime()), timeDifference)); } }); } }
Key Details:
- Up-to-date current time: We fetch the current time inside the
onTimeChangedmethod, so it always reflects the exact moment the user selects a time. - Calendar-based calculation: Using
Calendarobjects lets us easily convert times to millisecond timestamps, which simplifies calculating the difference. - Readable output: We convert the raw millisecond difference into hours and minutes, and handle negative values (when the selected time is earlier in the day than the current time) by adding a minus sign.
- Clean formatting:
String.formatensures times are displayed with leading zeros (e.g., 09:05 instead of 9:5) for consistency.
内容的提问来源于stack exchange,提问作者HARSH ASHRA
相关产品推荐
相关产品推荐

