我想以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);
}
}
最佳答案
要计算两个日期之间的时差,您可以尝试如下操作:
long millis = date1.getTime() - date2.getTime();
int hours = (int) (millis / (1000 * 60 * 60));
int mins = (int) ((millis / (1000 * 60)) % 60)
String diff = hours + ":" + mins;
要每秒更新时差,您可以使用计时器。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);
}
关于android - 两次之间的时差,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15360123/