需求:做一个后台返回的制定时间戳,来做个倒计时,思路是 先获取本地时间,服务器的时间戳转换为时间,然后进行一个对比差,获取的秒数,然后用CountDownTimer 倒计时就可以了,先复制代码跑起来,再慢慢了解。
1.时间戳转分钟工具
```
public class TimeUtils {
private static final String TAG = TimeUtils.class.getSimpleName();
//根据时间戳 获取总共多少秒
public static long getTime(long timestamp) {
Date currentTime =new Date();
SimpleDateFormat formatter =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date1 = formatter.format(currentTime);
//服务器
String date2 =formatData("yyyy-MM-dd HH:mm:ss", timestamp);
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);
Log.i(TAG, "getTime: " + days);
long allMinus = (hours *3600) + (minutes *60);
return allMinus;
}catch (Exception e) {
}
return Long.parseLong(null);
}
public static String formatData(String dataFormat, long timeStamp) {
if (timeStamp ==0) {
return "";
}
timeStamp = timeStamp *1000;
String result ="";
SimpleDateFormat format =new SimpleDateFormat(dataFormat);
result = format.format(new Date(timeStamp));
return result;
}
//补零
public static String getZero(int number) {
DecimalFormat decimalFormat =new DecimalFormat("00");
String format = decimalFormat.format(number);
return format;
}
}
class MyCountextends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
LogUtil.i("onTick: " + millisUntilFinished);
int s = Integer.parseInt("" + millisUntilFinished /1000);
int hour = s /3600;
s = s %3600;
int minute = s /60;
s = s %60;
int second = s;
mTvHour.setText(TimeUtils .getZero(hour));
mTvMinute.setText(TimeUtils .getZero(minute));
mTvSecond.setText(TimeUtils .getZero(second));
}
@Override
public void onFinish() {
}
}
```
调用 :
long time = TimeUtils.getTime(“服务器时间戳”);//获得总共多少秒
MyCount myCount=new MyCount(time*1000, 1000); //第一个参数是毫秒 第二参数间隔刷新 比如 6000 1000 就是总共6秒 一秒刷新
myCount.start();
记得释放
@Override
public void onDestroy() {
super.onDestroy();
if (mMyCount !=null) {
mMyCount.cancel();
}
}