本文实例为大家分享了Android动态显示相聚时间的具体代码,供大家参考,具体内容如下
目标效果:
主要功能代码:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //初始化控件 info(); //立即调用该方法 handler.post(runnable); } //立即调用方法 Handler handler = new Handler(); Runnable runnable=new Runnable() { @Override public void run() { handler.postDelayed(runnable,1000); //计算相恋时间 culLoveDate(); } }; //初始化控件 private void info() { tvLoveDays= (TextView) findViewById(R.id.tvLoveDays); tvLoveHoursMinutesSecOnds= (TextView) findViewById(R.id.tvLoveHoursMinutesSeconds); } //计算相恋时间 private void culLoveDate() { SimpleDateFormat dfs=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long between = 0; try { Date begin = dfs.parse("2015-04-11 09:09:09"); //设置开始计算时间 Date end = new Date(System.currentTimeMillis());//获取当前时间 between = (end.getTime() - begin.getTime());// 得到两者的秒数 } catch (Exception ex) { ex.printStackTrace(); } long day = between / (24 * 60 * 60 * 1000); long hour = (between / (60 * 60 * 1000) - day * 24); long min = ((between / (60 * 1000)) - day * 24 * 60 - hour * 60); long sec = (between / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60); String loveDays="已相恋:"+day+"天"; String loveHoursMinutesSecOnds=hour+"时"+min+"分"+sec+"秒"; tvLoveDays.setText(loveDays); tvLoveHoursMinutesSeconds.setText(loveHoursMinutesSeconds); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。