在Android中计算两次之间的差异

biswetbf  于 2023-05-27  发布在  Android
关注(0)|答案(8)|浏览(191)

我有两个字符串变量,如StartTime和EndTime。我需要通过用StartTime减去EndTime来计算TotalTime。
StartTime和EndTime的格式如下:

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

小时和分钟格式的TotalTime。在Android中如何计算?

2ul0zpep

2ul0zpep1#

试试下面的代码。
//假设时间格式为**(“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);

产量-小时数::8

6za6bjd0

6za6bjd02#

注:以下由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);

结果将是:小时:9,分钟:0

ojsjcaue

ojsjcaue3#

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

对于日期差异

Date myDate = new Date(difference);

显示日期:

String diff = df.format(myDate);
balp4ylt

balp4ylt4#

请试试这个。。。

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

plupiseo5#

我想提供一个现代的答案。

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

此代码段的输出为:
小时和分钟格式的TotalTime为08:00
(在Java 1.7.0_67上测试,带有ThreeTen Backport。)
其他答案中使用的datetime类-SimpleDateFormatDateDateFormatCalendar-都是过时的,设计很差。可能更糟的是,一个答案是“手工”解析和计算,而不需要任何库类的帮助。这是复杂和容易出错的,从来没有推荐。相反,我使用的是java.time,现代的Java日期和时间API。和它一起工作要好得多。

问题:我可以在Android上使用java.time吗?

是的,java.time在较旧和较新的Android设备上都能很好地工作。它至少需要Java 6

  • 在Java 8和更高版本以及更新的Android设备(从API级别26开始)中,现代API是内置的。
  • 在Java 6和7中,获取ThreeTen Backport,这是现代类的backport(JSR 310为ThreeTen;见底部的链接)。
  • 在(旧版)Android上使用ThreeTen Backport的Android版本。它被称为ThreetenABP。并确保从org.threeten.bp导入日期和时间类及其子包:org.threeten.bp.Durationorg.threeten.bp.LocalTimeorg.threeten.bp.format.DateTimeFormatter

友情链接

vshtjzan

vshtjzan6#

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 + "";
}

我的输出是E/App---Time:361分钟

b1payxdu

b1payxdu7#

你可以在Kotlin中这样使用扩展函数:

fun Long.toTimeAgo(): String {
    val time = this
    val now = System.currentTimeMillis()

    // convert back to second
    val diff = (now - time) / 1000

    return diff.toString()
}

要获得社交格式的结果,可以将代码修改为:

fun Long.toTimeAgo(): String {
    val time = this
    val now = System.currentTimeMillis()

    // convert back to second
    val diff = (now - time) / 1000

    return when {
        diff < MINUTE -> "Just now"
        diff < 2 * MINUTE -> "a minute ago"
        diff < 60 * MINUTE -> "${diff / MINUTE} minutes ago"
        diff < 2 * HOUR -> "an hour ago"
        diff < 24 * HOUR -> "${diff / HOUR} hours ago"
        diff < 2 * DAY -> "a day ago"
        diff < 30 * DAY -> "${diff / DAY} days ago"
        diff < 2 * MONTH -> "a month ago"
        diff < 12 * MONTH -> "${diff / MONTH} months ago"
        diff < 2 * YEAR -> "a year ago"
        else -> "${diff / YEAR} years ago"
    }
}

现在在代码中,从字符串中的日期获取时间差,可以用途:

val date = SimpleDateFormat('your date pattern').parse(dateString)
    val timeString = date.time.toTimeAgo()
8cdiaqws

8cdiaqws8#

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

相关问题