APP(Android版)客户端与服务器端时间校准

APP开发人员经常会遇见一个bug就是,APP显示的时间不准,或者说APP时间与服务器时间不一致,会导致数据请求、数据显示等各种问题。这时候我们就需要一种机制来解决时间不一致的问题。

解决方案如下: 
1.服务器端永远使用UTC时间,包括参数和返回值,不要使用Date格式,而是使用UTC时间1970年1月1日的差值,即long类型的长整数。
2.APP端将服务器返回的long型时间转换为GMT8时区的时间,额外加上8小时,这样就保证了无论使用者在哪个时区,他们看到的时间都是同一个时间,也就是GMT8的时间。
3.APP本地时间会不准,少则差几分钟,多则十几分钟,要解决这个问题,我们可以使用HTTP Response头的Date属性,每次调用服务器接口时就取出HTTP Response头的Date值,转换为GMT时间,再减去本地取出的时间,得到一个差值d,我们将这个差值d保存下来。每次获取本地时间的时候,额外加上这个差值d,就得到了服务器的GMT8时间,就保证了任何人看见的时间都是一样的。
 

/**
 * 获取差值
 **/
private long getDeltaBetweenServerAndClientTime(Headers headers) {
        long deltaBetweenServerAndClientTime=0;
        if (headers!=null) {
           final String strServerDate = headers.get("Date");
            if (!TextUtils.isEmpty(strServerDate)){
                final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.ENGLISH);
                TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
                try {
                    Date serverDate  = simpleDateFormat.parse(strServerDate);
                    deltaBetweenServerAndClientTime = serverDate.getTime()-System.currentTimeMillis();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        return deltaBetweenServerAndClientTime;
    }

使用时加上差值:

Date serverTime  = new Date(System.currentTimeMillis()+deltaBetweenServerAndClientTime);

猜你喜欢

转载自blog.csdn.net/dabao87/article/details/84618943