Java 计算两次android之间的差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18908738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:13:15  来源:igfitidea点击:

Calculate difference between two times android

javaandroiddatetimesimpledateformat

提问by Dave

I am developing and android app, where I need to calculate the difference between two times.I need to calculate the time difference for 24 hrs, and also the difference between times on two days(Eg. 5pm today to 9 am tomorrow).

我正在开发和 android 应用程序,我需要计算两次之间的差异。我需要计算 24 小时的时差,以及两天的时间差(例如今天下午 5 点到明天上午 9 点)。

I have tried the below code, to calculate the difference which works only for 24 hrs,

我尝试了以下代码,以计算仅适用于 24 小时的差异,

String dateStart = "08:00:00";
String dateStop = "13:00:00";

//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");

Date d1 = null;
Date d2 = null;

try 
{
    d1 = format.parse(dateStart);
    d2 = format.parse(dateStop);

    //in milliseconds
    long diff = d2.getTime() - d1.getTime();
    long diffHours = diff / (60 * 60 * 1000) % 24;
    Log.e("test",diffHours + " hours, ");
}
catch (Exception e) 
{
    // TODO: handle exception
} 

回答by Yup

Sir, you can make it easily in using java feature. long difference = date2.getTime() - date1.getTime();Take a look in this linkthis will help you.

先生,您可以轻松地使用 java 功能。long difference = date2.getTime() - date1.getTime();看看这个链接,这会对你有所帮助。

回答by Srikanth Roopa

You can try something like this also if you are sure the 9 am is next day you can add one day and calculate the difference:

如果您确定早上 9 点是第二天,您也可以尝试这样的事情,您可以添加一天并计算差异:

String string1 = "05:00:00 PM";
    Date time1 = new SimpleDateFormat("HH:mm:ss aa").parse(string1);
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(time1);

    String string2 = "09:00:00 AM";
    Date time2 = new SimpleDateFormat("HH:mm:ss aa").parse(string2);
    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTime(time2);
    calendar2.add(Calendar.DATE, 1);

    Date x = calendar1.getTime();
    Date xy = calendar2.getTime();
    long diff = x.getTime() - xy.getTime();
    diffMinutes = diff / (60 * 1000);
    float diffHours = diffMinutes / 60;
    System.out.println("diff hours" + diffHours);

回答by Pratima

I worked it out this way:

我是这样解决的:

Date time1 = new SimpleDateFormat("HH:mm:ss aa").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);

Date time2 = new SimpleDateFormat("HH:mm:ss aa").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);

if(calendar2.get(Calendar.AM_PM) == 1 && calendar1.get(Calendar.AM_PM) == 0)     {
     calendar2.add(Calendar.DATE, 1);
}
long diff = calendar1.getTimeInMillis() - calendar2.getTimeInMillis()

This will help to find the difference in time round the clock.

这将有助于找到全天候的时间差异。

回答by Kalpesh

Correct way to find proper time difference:

找到正确时差的正确方法:

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

回答by Syed Danish Haider

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

回答by Basil Bourque

tl;dr

tl;博士

ChronoUnit.HOURS.between( 
    LocalTime.parse( "08:00:00" ) , 
    LocalTime.parse( "13:00:00" ) 
)

5

5

…or…

…或者…

ChronoUnit.HOURS.between( 
    ZonedDateTime.of( 
        LocalDate.of( 2017 , Month.JANUARY , 23 ) ,
        LocalTime.parse( "08:00:00" ) , 
        ZoneId.of( "America/Montreal" )
    ) , 
    ZonedDateTime.of( 
        LocalDate.of( 2017 , Month.JANUARY , 25 ) ,
        LocalTime.parse( "13:00:00" ) , 
        ZoneId.of( "America/Montreal" )
    ) 
) 

53

53

java.time

时间

Modern approach uses the java.time classes.

现代方法使用 java.time 类。

LocalTime

LocalTime

The LocalTimeclass represents a time-of-day without a date and without a time zone.

LocalTime级表示没有日期,没有一个时区时间的一天。

LocalTime start = LocalTime.parse( "08:00:00" ) ;
LocalTime stop = LocalTime.parse( "13:00:00" ) ;

Duration

Duration

Get a Durationobject to represent the span-of-time.

获取一个Duration对象来表示时间跨度。

Duration d = Duration.between( start , stop ) ;

ChronoUnit

ChronoUnit

For number of hours, use ChronoUnit.

对于小时数,请使用ChronoUnit.

long hours = ChronoUnit.HOURS.between( start , stop ) ;

Android

安卓

For Android, see the ThreeTen-Backport and ThreeTenABP projects. See last bullets below.

对于 Android,请参阅 ThreeTen-Backport 和 ThreeTenABP 项目。请参阅下面的最后一个项目符号。

ZonedDateTime

ZonedDateTime

If you want to cross days, going past midnight, you must assign dates and time zones.

如果您想跨越几天,越过午夜,您必须指定日期和时区。

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris Franceis a new day while still “yesterday” in Montréal Québec.

时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。

Specify a proper time zone namein the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as ESTor ISTas they are nottrue time zones, not standardized, and not even unique(!).

以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/regionAmerica/MontrealAfrica/CasablancaPacific/AucklandESTIST

ZoneId z = ZoneId.of( "America/Montreal" ) ;

ZonedDateTime start = ZonedDateTime.of( 
    LocalDate.of( 2017 , Month.JANUARY , 23 ) ,
    LocalTime.parse( "08:00:00" ) , 
    z
) ;

ZonedDateTime stop = ZonedDateTime.of( 
    LocalDate.of( 2017 , Month.JANUARY , 25 ) ,
    LocalTime.parse( "13:00:00" ) , 
    z
) ;

long hours = ChronoUnit.HOURS.between( start , stop ) ;

See this code run live at IdeOne.com.

查看此代码在 IdeOne.com 上实时运行

53

53



About java.time

关于 java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

Where to obtain the java.time classes?

从哪里获得 java.time 类?