简体   繁体   English

计算Android中两次之间的差异

[英]Calculate Difference between two times in Android

I have two string variables such as StartTime and EndTime.我有两个字符串变量,例如 StartTime 和 EndTime。 I need to Calculate the TotalTime by subtracting the EndTime with StartTime.我需要通过用 StartTime 减去 EndTime 来计算 TotalTime。

The Format of StartTime and EndTime is as like follows: StartTime 和 EndTime 的格式如下:

StartTime = "08:00 AM";
EndTime = "04:00 PM";

TotalTime in Hours and Mins Format.以小时和分钟格式表示的总时间。 How to calculate this in Android?如何在Android中计算这个?

Try below code.试试下面的代码。

// suppose time format is into ("hh:mm a") format // 假设时间格式为("hh:mm a")格式

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a");

date1 = simpleDateFormat.parse("08:00 AM");
date2 = simpleDateFormat.parse("04:00 PM");

long 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);

Output - Hours :: 8输出- 小时 :: 8

Note: Corrected code as below which provide by Chirag Raval because in code which Chirag provided had some issues when we try to find time from 22:00 to 07:00.注意:更正了以下由 Chirag Raval 提供的代码,因为在 Chirag 提供的代码中,当我们尝试查找 22:00 到 07:00 的时间时存在一些问题。

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
Date startDate = simpleDateFormat.parse("22:00");
Date endDate = simpleDateFormat.parse("07:00");

long difference = endDate.getTime() - startDate.getTime(); 
if(difference<0)
{
    Date dateMax = simpleDateFormat.parse("24:00");
    Date dateMin = simpleDateFormat.parse("00:00");
    difference=(dateMax.getTime() -startDate.getTime() )+(endDate.getTime()-dateMin.getTime());
}
int days = (int) (difference / (1000*60*60*24));  
int hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60)); 
int min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
Log.i("log_tag","Hours: "+hours+", Mins: "+min); 

Result will be: Hours: 9, Mins: 0结果将是:小时:9,分钟:0

Have a look at DateFormat , you can use it to parse your strings with the parse(String source) method and the you can easily manipulate the two Dates object to obtain what you want.看看DateFormat ,您可以使用它通过 parse(String source) 方法解析您的字符串,并且您可以轻松操作两个 Dates 对象以获得您想要的内容。

DateFormat df = DateFormat.getInstance();
Date date1 = df.parse(string1);
Date date2 = df.parse(string2);
long difference = date1.getTime() - date2.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);

String diffHours = df.format(hours);

For date difference对于日期差异

Date myDate = new Date(difference);

The to show the Date :显示日期:

String diff = df.format(myDate);

Please try this....请试试这个....

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");

    try {
        date1 = simpleDateFormat.parse("08:00 AM");
    } catch (ParseException e) {
        e.printStackTrace();
    }

    try {
        date2 = simpleDateFormat.parse("04:00 PM");
    } catch (ParseException e) {
        e.printStackTrace();
    }

    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));
    int min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours))
            / (1000 * 60);
    hours = (hours < 0 ? -hours : hours);
    Log.i("======= Hours", " :: " + hours);

I should like to contribute the modern answer.我想贡献现代答案。

java.time and ThreeTenABP java.time 和 ThreeTenABP

    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);

    String startTime = "08:00 AM";
    String endTime = "04:00 PM";

    LocalTime start = LocalTime.parse(startTime, timeFormatter);
    LocalTime end = LocalTime.parse(endTime, timeFormatter);

    Duration diff = Duration.between(start, end);

    long hours = diff.toHours();
    long minutes = diff.minusHours(hours).toMinutes();
    String totalTimeString = String.format("%02d:%02d", hours, minutes);
    System.out.println("TotalTime in Hours and Mins Format is " + totalTimeString);

The output from this snippet is:此代码段的输出是:

TotalTime in Hours and Mins Format is 08:00以小时和分钟为单位的总时间为 08:00

(Tested on Java 1.7.0_67 with ThreeTen Backport.) (使用 ThreeTen Backport 在 Java 1.7.0_67 上测试。)

The datetime classes used in the other answers — SimpleDateFormat , Date , DateFormat and Calendar — are all long outdated and poorly designed.其他答案中使用的日期时间类 — SimpleDateFormatDateDateFormatCalendar — 都早已过时且设计不佳。 Possibly worse, one answer is parsing and calculating “by hand”, without aid from any library classes.可能更糟糕的是,一个答案是“手动”解析和计算,无需任何库类的帮助。 That is complicated and error-prone and never recommended.这是复杂且容易出错的,从不推荐。 Instead I am using java.time, the modern Java date and time API.相反,我使用的是 java.time,现代 Java 日期和时间 API。 It is so much nicer to work with.和它一起工作要好得多。

Question: Can I use java.time on Android?问题:我可以在 Android 上使用 java.time 吗?

Yes, java.time works nicely on older and newer Android devices.是的,java.time 在较旧和较新的 Android 设备上都能很好地工作。 It just requires at least Java 6 .它只需要至少Java 6

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.在 Java 8 及更高版本和更新的 Android 设备(从 API 级别 26)中,现代 API 是内置的。
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).在 Java 6 和 7 中获得 ThreeTen Backport,现代类的 backport(ThreeTen for JSR 310;请参阅底部的链接)。
  • On (older) Android use the Android edition of ThreeTen Backport.在(较旧的)Android 上使用 ThreeTen Backport 的 Android 版本。 It's called ThreeTenABP.它被称为 ThreeTenABP。 And make sure you import the date and time classes from org.threeten.bp with subpackages: org.threeten.bp.Duration , org.threeten.bp.LocalTime and org.threeten.bp.format.DateTimeFormatter .并确保您使用子包从org.threeten.bp导入日期和时间类: org.threeten.bp.Durationorg.threeten.bp.LocalTimeorg.threeten.bp.format.DateTimeFormatter

Links链接

String mStrDifferenceTime =compareTwoTimeAMPM("11:06 PM","05:07 AM");
Log.e("App---Time ", mStrDifferenceTime+" Minutes");

public static String getCurrentDateUsingCalendar() {
    Date mDate = new Date();  // to get the date
    @SuppressLint("SimpleDateFormat") SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("dd-MM-yyyy"); // getting date in this format
    return mSimpleDateFormat.format(mDate.getTime());
}

public static String getNextDateUsingCalendar() {
    Calendar mCalendar = Calendar.getInstance();
    mCalendar.add(Calendar.DAY_OF_YEAR, 1);
    Date mStrTomorrow = mCalendar.getTime();
    @SuppressLint("SimpleDateFormat") DateFormat mDateFormat = new SimpleDateFormat("dd-MM-yyyy");
    return mDateFormat.format(mStrTomorrow);

}

public static String compareTwoTimeAMPM(String mStrStartTime, String mStrEndTime) {
    String mStrCompareStartTime[] = mStrStartTime.split(" ");
    String mStrCompareEndTime[] = mStrEndTime.split(" ");
    int mIStartTime = Integer.parseInt(mStrCompareStartTime[0].replace(":", ""));
    int mIEndTime = Integer.parseInt(mStrCompareEndTime[0].replace(":", ""));
    String mStrToday = "";
    String mStrTomorrow = "";
    if (mIStartTime < mIEndTime && mStrCompareStartTime[1].equals("PM") && mStrCompareEndTime[1].equals("PM")) {
        mStrToday = getCurrentDateUsingCalendar();
        mStrTomorrow = getCurrentDateUsingCalendar();
    } else if (mIStartTime < mIEndTime && mStrCompareStartTime[1].equals("AM") && mStrCompareEndTime[1].equals("AM")) {
        mStrToday = getCurrentDateUsingCalendar();
        mStrTomorrow = getCurrentDateUsingCalendar();
    } else if (mIStartTime > mIEndTime && mStrCompareStartTime[1].equals("PM") && mStrCompareEndTime[1].equals("PM")) {
        String mStrTime12[] = mStrCompareStartTime[0].split(":");
        if (mStrTime12[0].equals("12")) {
            mStrToday = getNextDateUsingCalendar();
            mStrTomorrow = getNextDateUsingCalendar();
        } else {
            mStrToday = getCurrentDateUsingCalendar();
            mStrTomorrow = getNextDateUsingCalendar();
        }
    } else if (mIStartTime > mIEndTime && mStrCompareStartTime[1].equals("AM") && mStrCompareEndTime[1].equals("AM")) {
        String mStrTime12[] = mStrCompareStartTime[0].split(":");
        if (mStrTime12[0].equals("12")) {
            mStrToday = getNextDateUsingCalendar();
            mStrTomorrow = getNextDateUsingCalendar();
        } else {
            mStrToday = getCurrentDateUsingCalendar();
            mStrTomorrow = getNextDateUsingCalendar();
        }
    } else if (mStrCompareStartTime[1].equals("PM") && mStrCompareEndTime[1].equals("AM")) {
        mStrToday = getCurrentDateUsingCalendar();
        mStrTomorrow = getNextDateUsingCalendar();
    } else if (mStrCompareStartTime[1].equals("AM") && mStrCompareEndTime[1].equals("PM")) {
        mStrToday = getCurrentDateUsingCalendar();
        mStrTomorrow = getCurrentDateUsingCalendar();
    }
    @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm aa");
    String mStrDifference = "";
    try {
        Date date1 = simpleDateFormat.parse(mStrToday + " " + mStrStartTime);
        Date date2 = simpleDateFormat.parse(mStrTomorrow + " " + mStrEndTime);
        mStrDifference = differenceDatesAndTime(date1, date2);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return mStrDifference;

}


public static String differenceDatesAndTime(Date mDateStart, Date mDateEnd) {

    long different = mDateEnd.getTime() - mDateStart.getTime();
    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    long elapsedDays = different / daysInMilli;
    different = different % daysInMilli;

    long elapsedHours = different / hoursInMilli;
    different = different % hoursInMilli;

    long elapsedMinutes = different / minutesInMilli;

    long minutes = elapsedHours * 60 + elapsedMinutes;
    long result = elapsedDays * 24 * 60 + minutes;
    if (0 > result) {
        result = result + 720;  //result is minus then add 12*60 minutes
    }

    return result + "";
}

My output is E/App---Time: 361 Minutes我的输出是 E/App---时间:361 分钟

Try simple piece of code using For 24 hour time
StartTime = "10:00";
EndTime = "13:00";
here starthour=10 and end hour=13 
if(TextUtils.isEmpty(txtDate.getText().toString())||TextUtils.isEmpty(txtDate1.getText().toString())||TextUtils.isEmpty(txtTime.getText().toString())||TextUtils.isEmpty(txtTime1.getText().toString()))
    {
        Toast.makeText(getApplicationContext(), "Date/Time fields cannot be blank", Toast.LENGTH_SHORT).show();
    }
    else {
        if (starthour > endhour) {
            Toast.makeText(getApplicationContext(), "Start Time Should Be Less Than End Time", Toast.LENGTH_SHORT).show();
        } else if (starthour == endhour) {
            if (startmin > endmin) {
                Toast.makeText(getApplicationContext(), "Start Time Should Be Less Than End Time", Toast.LENGTH_SHORT).show();
            }
            else{
                tvalid = "True";
            }
        } else {
            // Toast.makeText(getApplicationContext(),"Sucess"+(endhour-starthour)+(endmin-startmin),Toast.LENGTH_SHORT).show();
            tvalid = "True";
        }
    }
same for date also

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM