how to get minutes difference between two time in android

被刻印的时光 ゝ 提交于 2019-12-24 13:57:46

问题


public int difftime(String string, String string2) {
        int hours;
        int min = 0;
        int days;
        long difference ;
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
            Date date1 = simpleDateFormat.parse("08:00 AM");
            Date date2 = simpleDateFormat.parse("04:00 PM");

             difference = date2.getTime() - date1.getTime();
             days = (int) (difference / (1000 * 60 * 60 * 24));
            hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
             min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours))
                    / (1000 * 60);
            hours = (hours < 0 ? -hours : hours);
            Log.i("======= Hours", " :: " + hours);
            return min;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return min;
    }

This is my function to get time difference in the form of minutes but it give always zero. I don't know where i did mistake please tell me where am doing mistake. I want result in the form of minutes.


回答1:


First of all, you did very basic mistake. For 12-hour system, you should use hh not HH. And I am amazed to see that, none of the answers correct this mistake.

Secondly, you're not considering Date rather only depending upon the time. So 08:00AM and 04:00PM doesn't have any minute difference. It only have 8 hours difference.

So, now in your case, you have to calculate minutes based on two scenarios i-e one from Hours and one when there is minutes difference. I correct your code. Please Check it as this is working as expected at my end.

public long diffTime() {
    long min = 0;
    long difference ;
    try {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm aa"); // for 12-hour system, hh should be used instead of HH
        // There is no minute different between the two, only 8 hours difference. We are not considering Date, So minute will always remain 0
        Date date1 = simpleDateFormat.parse("08:00 AM");
        Date date2 = simpleDateFormat.parse("04:00 PM");

        difference = (date2.getTime() - date1.getTime()) / 1000;
        long hours = difference % (24 * 3600) / 3600; // Calculating Hours
        long minute = difference % 3600 / 60; // Calculating minutes if there is any minutes difference
        min = minute + (hours * 60); // This will be our final minutes. Multiplying by 60 as 1 hour contains 60 mins
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return min;
}



回答2:


a simple example hope it will help you :)

SimpleDateFormat dfDate  = new SimpleDateFormat("HH:mm a");
java.util.Date d = null;
java.util.Date d1 = null;
Calendar cal = Calendar.getInstance();
try {
        d = dfDate.parse("08:00 AM");
        d1 = dfDate.parse("04:00 PM");
    } catch (java.text.ParseException e) {
        e.printStackTrace();
    }

long diffInTime = (long) ((d.getTime() - d1.getTime())/ (1000 * 60 * 60 * 
24));
long minutes = TimeUnit.MILLISECONDS.toMinutes(diffInTime); <--- converting 
the result in minutes
System.out.println(minutes);



回答3:


Mulitply be 24 more to get hours and than MINUTES

1> parse exception

2> you are not getting difference in MINUTE so do that you need to change

Change ,

hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60)); 

TO

hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60 * 24));

check

public int difftime() {
        int hours;
        int min = 0;
        int days;
        long difference;
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
            Date date1 = simpleDateFormat.parse("08:00 AM");
            Date date2 = simpleDateFormat.parse("04:00 PM");

            difference = date2.getTime() - date1.getTime();
            days = (int) (difference / (1000 * 60 * 60 * 24));
            hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60 * 24));
            min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours)) / (1000 * 60);
            hours = (hours < 0 ? -hours : hours);
            Log.e("======= Hours", " :: " + hours);
            Log.e("======= min", " :: " + min);
            return min;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return min;
    }



回答4:


Try using the TimeUnit class in java. This will convert the long value in Millis that you recieve into hours and mins.

    int hours;
    int min;
    long difference ;

    try {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        Date date1 = simpleDateFormat.parse("08:00 AM");
        Date date2 = simpleDateFormat.parse("04:00 PM");

        difference = date2.getTime() - date1.getTime();

        hours = Long.valueOf(TimeUnit.MILLISECONDS.toHours(difference)).intValue();
        min = Long.valueOf(TimeUnit.MILLISECONDS.toMinutes(difference)).intValue();

        hours = (hours < 0 ? -hours : hours);
        Log.i("======= Hours", " :: " + hours);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



回答5:


you can try this it works for me. In this example, I calculate the difference between hours and minutes and I ignore the day and the year fields.

public static Date getDate(int hour, int minute) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, 0);
    cal.set(Calendar.MONTH, 0);
    cal.set(Calendar.DAY_OF_MONTH, 0);
    cal.set(Calendar.HOUR_OF_DAY, hour);
    cal.set(Calendar.MINUTE, minute);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTime();
}

public static int getDiff(Date date1, Date date2){
    /* this function get the difference between date1 and date2
     * represented in minutes
     * assume that the formate is HH:MM */
    int min = 0;
    int hr = 0;
    if (date1.getMinutes() >= date2.getMinutes()){
        min = date1.getMinutes() - date2.getMinutes();
    }else{
        min = date1.getMinutes() + ( 60 - date2.getMinutes());
        hr = -1;
    }
    if ((date1.getHours()+hr) >= date2.getHours()){
        hr += date1.getHours() - date2.getHours();
    }else{
        hr += date1.getHours() + (24 - date2.getHours());
    }
    return min + (hr * 60);
}

the first function to create Date and the second to get the difference

then you can get the difference like below

Date currentTime = Calendar.getInstance().getTime();
Date secondTime = getDate(11,5);    this will be 11:05
int diff = getDiff(secondTime ,currentTime);

diff will represent the number of minutes you will spend between the current time till you reach the secondTime.




回答6:


This worked for me,I have two textview and i am using timepicker to set time

case R.id.starttime_activityentry:

                 mcurrentTime = Calendar.getInstance();
                 hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
                 minutes = mcurrentTime.get(Calendar.MINUTE);
                TimePickerDialog mTimePicker;
                mTimePicker = new TimePickerDialog(ActivityEntryDetail.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                        starttime.setText( selectedHour + ":" + selectedMinute);
                    }
                }, hour, minutes, true);//Yes 24 hour time
                mTimePicker.setTitle("Select Time");
                mTimePicker.show();


                break;


            case R.id.endtime_activityentry:



                 endmcurrentTime = Calendar.getInstance();
                 endhour = endmcurrentTime.get(Calendar.HOUR_OF_DAY);
                 endminute = endmcurrentTime.get(Calendar.MINUTE);
                TimePickerDialog endmTimePicker;
                endmTimePicker = new TimePickerDialog(ActivityEntryDetail.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                        endtime.setText( selectedHour + ":" + selectedMinute);


                    }
                }, endhour, endminute, true);//Yes 24 hour time
                endmTimePicker.setTitle("Select Time");

And take one button to show difference

case R.id.durations:

               hourdifs();
                break;

Call this method

public static void hourdifs()
    {


        try {

            String sttime= starttime.getText().toString();
            System.out.println("sttime before parse DATE"+sttime);

            String endtm= endtime.getText().toString();
            System.out.println("endtmie before parse DATE"+endtm);

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
            Date date1 = simpleDateFormat.parse(sttime);
            Date date2 = simpleDateFormat.parse(endtm);

            long difference = date2.getTime() - date1.getTime();
           int days = (int) (difference / (1000*60*60*24));
           int hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60 * 24));
          int  min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
            hours = (hours < 0 ? -hours : hours);
            Log.i("=== Hours"," :: "+hours+":"+min);



        }
        catch (Exception j){
            j.printStackTrace();
        }

    }


来源:https://stackoverflow.com/questions/36913996/how-to-get-minutes-difference-between-two-time-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!