羊皮书APP(Android版)开发系列(十一)客户端与服务器端时间校准

来源:互联网 发布:水果编曲软件 编辑:程序博客网 时间:2024/05/01 10:38

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时间,就保证了任何人看见的时间都是一样的。
    4. 一个案例:
/** * 获取差值 **/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);

  • 原文地址:http://blog.csdn.net/wjwj1203/article/details/50902113
  • 我的github地址:https://github.com/wjie2014
  • 我的博客地址:http://blog.studyou.cn/
  • 我的CSDN博客地址:http://blog.csdn.net/wjwj1203
  • 我的Gmail邮箱:w489657152@gmail.com

0 0