Android-从TimePicker中选择的时间减去当前时间

问题描述

我想从时间选择器(即SelectedTime - Current Time)中选择的时间减去当前时间。因此,我知道如何从时间选择器中获取当前时间和选定时间。

以下是代码

public class ScheduleMessage extends AppCompatActivity {

    TextView textView;
    TimePicker timePicker;
    String date,currentTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedule_message);

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm ");
        currentTime = timeFormat.format(calendar.getTime());

        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) {
                date = hourOfDay + ":" + minute;
                textView.setText(date + "---" + currentTime);
            }

        });

    }
}

那么,我怎么减去它呢?有帮助吗?

解决方法

在确定日期之间的差异时,您可以进行以下操作

SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");// or you can add before dd/M/yyyy

Date date1 = format.parse("08:00:12 pm");
Date date2 = format.parse("05:30:12 pm");

long mills = date1.getTime() - date2.getTime();
               
int hours = (int) (mills/(1000 * 60 * 60));
int mins = (int) (mills/(1000*60)) % 60;

String diff = hours + ":" + mins;
,

如果您有字符串,则需要使用java.text.SimpleDateFormat将其解析为java.util.Date。像这样:

 java.text.DateFormat df = new java.text.SimpleDateFormat("hh:mm:ss");
    java.util.Date date1 = df.parse("18:40:10");
    java.util.Date date2 = df.parse("19:05:15");
    long diff = date2.getTime() - date1.getTime();