1.设置开始时间:
// 设置请求买单的时间 String createTime = order.getCreateTime(); SimpleDateFormat tableDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date tableDate = null; try { tableDate = tableDateFormat.parse(createTime); } catch (ParseException e) { tableDate = new Date(); } SimpleDateFormat tableFormat = new SimpleDateFormat("HH:mm:ss"); String tableTime = tableFormat.format(tableDate); tvTableTime.setText(tableTime); // 设置买单计时 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); //1.以服务器时间为准开始计时 // try { // startData = dateFormat.parse(createTime); // } catch (ParseException e) { // startData = new Date(); // } finally { // 开始计时 // new Thread(this).start(); // } //2.以手机时间为准开始计时 startData = new Date(); new Thread(this).start();
2.更新到UI显示效果:
@Override public void run() { while (!isStop) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } finally { String time = StringUtils.calcCurrentTime(startData); Message msg = handler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putString("time", time); msg.setData(bundle); msg.sendToTarget(); } } } Handler handler = new Handler() { public void handleMessage(Message msg) { Bundle bundle = msg.getData(); String time = bundle.getString("time"); tvTime.setText(time); }; };
/** * 计算当前时间差 * * @param startTime * @return */ public static String calcCurrentTime(Date startData) { Date now = new Date(System.currentTimeMillis());// 获取当前时间 long l = now.getTime() - startData.getTime(); long day = l / (24 * 60 * 60 * 1000); long hour = (l / (60 * 60 * 1000) - day * 24); long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60); long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60); return String.format("%02d:%02d:%02d", hour, min, s); }
/** * 计算当前时间差 * * @param startTime * @return */ @SuppressWarnings("finally") public static String calcCurrentTime(Date startData) { Date now = null;// 获取当前时间 try { now = getNetDate(); } catch (IOException e) { now = new Date(System.currentTimeMillis());// 获取当前时间 } finally { long l = now.getTime() - startData.getTime(); long day = l / (24 * 60 * 60 * 1000); long hour = (l / (60 * 60 * 1000) - day * 24); long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60); long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60); return String.format("%02d:%02d:%02d", hour, min, s); } } /** * 获取网络时间 * * @return * @throws IOException */ private static Date getNetDate() throws IOException { URL url = new URL("http://open.baidu.com/special/time/");// 取得资源对象 URLConnection uc = url.openConnection();// 生成连接对象 uc.connect();// 发出连接 long ld = uc.getDate(); // 取得网站日期时间 Date date = new Date(ld); // 转换为标准时间对象 return date; }