获取本地时间会因用户设定而造成错乱,因此需要应用去获取远程服务器时间。如果你没有自己的服务器开展业务,也可以使用互联网公司提供的时间API接口。

直接访问 http://quan.suning.com/getSysTime.do 可以看到接口提供的时间格式

{  "sysTime2": "2019-04-19 10:23:04",  "sysTime1": "20190419102304"}

里面有两个时间数据 sysTime2 和 sysTime1,都是常见的时间格式,但我们在计算和存储都是以时间戳的形式,所以获取到时间后会对其进行转换。

获取时间

由于是获取网络数据,需要在 Androidmanifest.xml 文件中申请网络使用权限。

再写一个网络请求的类,用于加载远程数据。

package com.example.gettime;import android.util.Log;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.ProtocolException;import java.net.URL;public class HttpHandler {    private static final String TAG = "HttpHandler";    public HttpHandler() {    }    public String makeServiceCall(String reqUrl) {        String response = null;        try {            URL url = new URL(reqUrl);            HttpURLConnection conn = (HttpURLConnection) url.openConnection();            conn.setRequestMethod("GET");            // read the response            InputStream in = new BufferedInputStream(conn.getInputStream());            response = convertStreamToString(in);        } catch (MalformedURLException e) {            Log.e(TAG, "MalformedURLException: " + e.getMessage());        } catch (ProtocolException e) {            Log.e(TAG, "ProtocolException: " + e.getMessage());        } catch (IOException e) {            Log.e(TAG, "IOException: " + e.getMessage());        } catch (Exception e) {            Log.e(TAG, "Exception: " + e.getMessage());        }        return response;    }    private String convertStreamToString(InputStream is) {        BufferedReader reader = new BufferedReader(new InputStreamReader(is));        StringBuilder sb = new StringBuilder();        String line;        try {            while ((line = reader.readLine()) != null) {                sb.append(line).append('\n');            }        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                is.close();            } catch (IOException e) {                e.printStackTrace();            }        }        return sb.toString();    }}

以下是封装好的方法

获取时间 getServerTimestamp

public static final int getServerTimestamp() {final HttpHandler httpHandler = new HttpHandler();final String jsonStr = httpHandler.makeServiceCall("http://quan.suning.com/getSysTime.do");if (jsonStr != null) {try {final JSONObject json = new JSONObject(jsonStr);if (json.has("sysTime2")) {final String date = json.getString("sysTime2");return dateToTimestamp(date);}} catch (JSONException e) {// e.printStackTrace();}}// 未能获取远程时间,将获取本地时间,根据需要修改.return Integer.valueOf(new Date().getTime()/1000+"");}

转换时间 dateToTimestamp

public static final int dateToTimestamp(String time) {    final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    final Date date;    try {        date = dateFormat.parse(time);    } catch (ParseException e) {        return 0;    }    return Integer.valueOf(date.getTime()/1000+"");}

 

更多相关文章

  1. SpringBoot 2.0 中 HikariCP 数据库连接池原理解析
  2. 一句话锁定MySQL数据占用元凶
  3. Android一周时间早中晚排班表
  4. Android(安卓)两个Fragment之间传递数据实例详解
  5. RxJava2 学习笔记
  6. 1-Android基础知识
  7. 获取Android设备信息
  8. Android(安卓)EditText获取焦点后只显示光标不弹出软键盘
  9. Android获取文件夹路径 /data/data/

随机推荐

  1. android 全屏问题
  2. 判断android网络连接
  3. Android中利用DisplayMetrics取得手机屏
  4. Android遇到 android studio "Internal H
  5. 在编译Android时,开机不锁屏
  6. Android(安卓)  收集索引贴
  7. Scrollview和RecyclerView滑动冲突问题解
  8. Android(安卓)studio 学习3:实现倒计时、
  9. Android(安卓)自定义APP开机启动,并打开其
  10. Android取消EditText自动获取焦点