两次之间的时差

时间:2013-03-12 11:38:10

标签: android time

我想以hh:mm格式显示两次之间的差异。

第一次来自数据库,第二次是系统时间。时差每秒更新一次。

我该怎么做?

目前我正在使用两个手动时间,如果这完全有效,那么我将其应用到我的应用程序中。

public class MainActivity extends Activity 
{
    TextView mytext;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Timer updateTimer = new Timer();
        updateTimer.schedule(new TimerTask() 
        {
            public void run() 
            {
                try 
                {
                    TextView txtCurrentTime= (TextView)findViewById(R.id.mytext);
                    SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
                    Date date1 = format.parse("08:00:12 pm");
                    Date date2 = format.parse("05:30:12 pm");
                    long mills = date1.getTime() - date2.getTime();
                    Log.v("Data1", ""+date1.getTime());
                    Log.v("Data2", ""+date2.getTime());
                    int hours = (int) (mills/(1000 * 60 * 60));
                    int mins = (int) (mills % (1000*60*60));

                    String diff = hours + ":" + mins; // updated value every1 second
                    txtCurrentTime.setText(diff);
                } 
                catch (Exception e) 
                {
                    e.printStackTrace();
                }
            }

        }, 0, 1000);
    }
}

8 个答案:

答案 0 :(得分:29)

要计算两个日期之间的差异,您可以尝试以下方法:

long mills = date1.getTime() - date2.getTime();
int hours = millis/(1000 * 60 * 60);
int mins = (mills/(1000*60)) % 60;

String diff = hours + ":" + mins; 

要每秒更新一次时差,您可以使用Timer。

Timer updateTimer = new Timer();
updateTimer.schedule(new TimerTask() {
    public void run() {
        try {
            long mills = date1.getTime() - date2.getTime();
                int hours = millis/(1000 * 60 * 60);
                 int mins = (mills/(1000*60)) % 60;

                 String diff = hours + ":" + mins; // updated value every1 second
            } catch (Exception e) {
            e.printStackTrace();
        }
    }

}, 0, 1000); // here 1000 means 1000 mills i.e. 1 second

编辑:工作代码:

public class MainActivity extends Activity {

    private TextView txtCurrentTime;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtCurrentTime= (TextView)findViewById(R.id.mytext);
        Timer updateTimer = new Timer();
        updateTimer.schedule(new TimerTask() 
        {
            public void run() 
            {
                try 
                {

                    SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
                    Date date1 = format.parse("08:00:12 pm");
                    Date date2 = format.parse("05:30:12 pm");
                    long mills = date1.getTime() - date2.getTime();
                    Log.v("Data1", ""+date1.getTime());
                    Log.v("Data2", ""+date2.getTime());
                    int hours = (int) (mills/(1000 * 60 * 60));
                    int mins = (int) (mills/(1000*60)) % 60;

                    String diff = hours + ":" + mins; // updated value every1 second
                    txtCurrentTime.setText(diff);
                } 
                catch (Exception e) 
                {
                    e.printStackTrace();
                }
            }

        }, 0, 1000);
    }

答案 1 :(得分:7)

终于做到了yuppiiieee ......

package com.timedynamicllyupdate;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity 
{
    TextView current;
    private TextView txtCurrentTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Thread myThread = null;
        Runnable myRunnableThread = new CountDownRunner();
        myThread= new Thread(myRunnableThread);   
        myThread.start();

        current= (TextView)findViewById(R.id.current);
    }


    public void doWork() 
    {
        runOnUiThread(new Runnable() 
        {
            public void run() 
            {
                try
                {
                    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss aa");

                    txtCurrentTime= (TextView)findViewById(R.id.mytext);

                    Date systemDate = Calendar.getInstance().getTime();
                    String myDate = sdf.format(systemDate);
//                  txtCurrentTime.setText(myDate);

                    Date Date1 = sdf.parse(myDate);
                    Date Date2 = sdf.parse("02:50:00 pm");

                    long millse = Date1.getTime() - Date2.getTime();
                    long mills = Math.abs(millse);

                    int Hours = (int) (mills/(1000 * 60 * 60));
                    int Mins = (int) (mills/(1000*60)) % 60;
                    long Secs = (int) (mills / 1000) % 60;

                    String diff = Hours + ":" + Mins + ":" + Secs; // updated value every1 second
                    current.setText(diff);
                }
                catch (Exception e) 
                {

                }
            }
        });
    }

    class CountDownRunner implements Runnable
    {
        // @Override
        public void run() 
        {
            while(!Thread.currentThread().isInterrupted())
            {
                try 
                {
                    doWork();
                    Thread.sleep(1000); // Pause of 1 Second
                } 
                catch (InterruptedException e) 
                {
                        Thread.currentThread().interrupt();
                }
                catch(Exception e)
                {
                }
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

答案 2 :(得分:6)

使用java.time

现代的方法是使用java.time类来取代麻烦的旧日期时间类。

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

使用DateTimeFormatter类定义格式模式。

String inputStart = "08:00:12 pm".toUpperCase() ;
String inputStop = "05:30:12 pm".toUpperCase() ;

DateTimeFormatter f = DateTimeFormatter.ofPattern( "hh:mm:ss a" );
LocalTime start = LocalTime.parse( inputStart , f );
LocalTime stop = LocalTime.parse( inputStop , f );
  

start.toString():20:00:12

     

stop.toString():17:30:12

LocalTime课程在一个通用的24小时工作日内完成。所以它不考虑过夜。如果您想在几天之间进行交叉,则应使用ZonedDateTimeOffsetDateTimeLocalDateTime来代替所有日期时间对象,而不是仅限时间。

A Duration捕获未附加到时间轴的时间段。

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

致电toString会在标准ISO 8601 format for durationsPnYnMnDTnHnMnS中生成文字,其中P标记开头,T分隔年份从小时 - 分钟 - 秒开始的几个月。我强烈建议使用这种格式,而不是时钟时间不明确的“HH:MM:SS”格式。

如果您坚持使用模糊的时钟时间格式,在Java 9及更高版本中,您可以通过调用toHoursParttoMinutesParttoSecondsPart来构建该字符串。

在您的示例数据中,我们正在及时向后移动,从晚上8点到下午5点,结果是负数小时和分钟,负两个半小时。

  

d.toString():PT-2H-30M

请参阅此code run live at IdeOne.com

关于java.time

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

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

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

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如IntervalYearWeekYearQuartermore

答案 3 :(得分:2)

这个过程大致如下,

  1. 按以下方式将字符串实例转换为日期实例

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Date date = format.parse("2011-01-03");
    
  2. 假设你拥有的systemTime很长,表示自epoc以来的毫秒数,你现在可以执行以下操作

    long difference = longNow - date.getTime();
    int msPerHour = 1000*60*60;
    int hours = difference/secondPerHour;
    int minutes = difference % secondPerHour;
    

    其中longNow是包含系统时间的当前变量。

答案 4 :(得分:1)

好的,我在这里为你建立Funcion:

 public void omriFunction(){
    Date Start = null;
    Date End = null;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
    try {
        Start = simpleDateFormat.parse(04+":"+30);
        End = simpleDateFormat.parse(06+":"+45);}
    catch(ParseException e){
        //Some thing if its not working
    }

    long difference = End.getTime() - Start.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);
    if(hours < 0){
        hours+=24;
    }if(min < 0){
        float  newone = (float)min/60 ;
        min +=60;
        hours =(int) (hours +newone);}
    String c = hours+":"+min;
    Log.d("ANSWER",c);}
答案:2:15;在logcat中

答案 5 :(得分:0)

嗨,大家不确定我做错了什么,但这对我有帮助,希望我可以帮助其他人。

我的min以浮动格式计算,所以我使用了这个公式

long Min = time %  (1000*60*60)/(60*1000);
time is my date2.getTime() - date1.getTime();

快乐编码

答案 6 :(得分:0)

Tray下面的代码可获取两个小时之间的小时和分钟差异:

private static int getHoursDiff(Calendar c1, Calendar c2) {
            Date d1 = c1.getTime();
            Date d2 = c2.getTime();
            long mils = d1.getTime() - d2.getTime();
            int hourDiff = (int) (mils / (1000 * 60 * 60));
            return hourDiff;
        }

        private static int getMinuteDiff(Calendar c1, Calendar c2) {
            Date d1 = c1.getTime();
            Date d2 = c2.getTime();
            long mils = d1.getTime() - d2.getTime();
            int minuteFor = (int) (mils / (1000 * 60) % 60);
            return minuteFor;
        } }

答案 7 :(得分:0)

所以我一直在寻找一种方法,可以让我在 Kolin 的 2 Times 中获得 HH/MM/SS,这似乎是一个不错的方法。

它使用import org.threeten.bp

fun getTimedifference(startTime: LocalDateTime,  endTime: LocalDateTime): String {
        val startTimeInstant = startTime.atOffset(ZoneOffset.UTC).toInstant()
        val endTimeInstant = endTime.atOffset(ZoneOffset.UTC).toInstant()
        val duration = Duration.between(startTimeInstant, endTimeInstant)
        val days = duration.toDays()
        val hours = duration.toHours() - (days * 24)
        val min = duration.toMinutes() - (duration.toHours() * 60)
        val sec = (duration.toMillis() / 1000) - (duration.toMinutes() * 60)
        return "${hours}:${min}:${sec}"
    }