计算两次android之间的差异

时间:2013-09-20 04:18:52

标签: java android date time simpledateformat

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

我尝试过以下代码,计算仅适用于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
} 

6 个答案:

答案 0 :(得分:13)

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

答案 1 :(得分:5)

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

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

答案 2 :(得分:4)

TL;博士

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

5

...或...

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

java.time

现代方法使用java.time类。

LocalTime

LocalTime类代表没有日期且没有时区的时间。

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

Duration

获取Duration个对象来表示时间范围。

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

ChronoUnit

对于小时数,请使用ChronoUnit

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

的Android

对于Android,请参阅ThreeTen-Backport和ThreeTenABP项目。见下面的子弹。

ZonedDateTime

如果你想跨越几天,过了午夜,你必须分配日期和时区。

时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因地区而异。例如,在Paris France午夜后的几分钟是新的一天,而Montréal Québec中仍然是“昨天”。

continent/region的格式指定proper time zone name,例如America/MontrealAfrica/CasablancaPacific/Auckland。切勿使用诸如ESTIST之类的3-4字母缩写,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

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

请参阅此code run live at IdeOne.com

  

53

关于java.time

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendar和&amp; SimpleDateFormat

现在位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

从哪里获取java.time类?

答案 3 :(得分:2)

如果您确定第二天上午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);

答案 4 :(得分:0)

我这样做了:

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

这将有助于及时找到时差。

答案 5 :(得分:0)

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