根据服务器时间戳 算倒计时

2019-06-12  本文已影响0人  键盘上的工匠者


效果图

1.获取本地时间

Date currentTime =new Date(); 

SimpleDateFormat formatter =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 

 String date1 = formatter.format(currentTime);

上面输出为    格式为:  2019-6-12 22:57:00

2.根据服务器的时间戳 算出年月  

//服务器 

String date2 =formatData("yyyy-MM-dd HH:mm:ss", timestamp);

3. 算出时间差

try {

   DateFormat df =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date d1 = df.parse(date2);

    Date d2 = df.parse(date1);

    long diff = d1.getTime() - d2.getTime();// 这样得到的差值是微秒级别

    long days = diff / (1000 *60 *60 *24);

    long hours = (diff - days * (1000 *60 *60 *24))/ (1000 *60 *60);

    long minutes = (diff - days * (1000 *60 *60 *24) - hours* (1000 *60 *60))/ (1000 *60);

}catch (Exception e) {

}

要抛出异常      返回   时  分  秒      

4.根据CountDownTimer  刷新数据

class MyCountextends CountDownTimer {

public MyCount(long millisInFuture, long countDownInterval) {

super(millisInFuture, countDownInterval);

    }

@Override

    public void onTick(long millisUntilFinished) {

        int s = Integer.parseInt("" + millisUntilFinished /1000);

        int mhours = s /3600;

        s = s %3600;

        int mMinute = s /60;

        s = s %60;

        int mSecond = s;

        //输出   时  分  秒  

    }

@Override

    public void onFinish() {

}

}

调用 : 

MyCount myCount=new MyCount(time*1000, 1000);    //第一个参数是毫秒  第二参数间隔刷新   比如  6000   1000    就是总共6秒  一秒刷新

 myCount.start();

记得注销

得到效果图   如下:

上一篇 下一篇

猜你喜欢

热点阅读