一、通过免费或者收费的API接口获取

1、免费
2、收费

详情:标准北京时间

二、通过访问某个地址并获取时间

1、HTTP协议访问某个网站

原理:HTTP协议的响应体中带有时间

HTTP/1.1 200 OK
Bdpagetype: 1
Bdqid: 0xf15515780000825e
Cache-Control: private
Connection: Keep-Alive
Content-Encoding: gzip
Content-Type: text/html
Cxy_all: baidu+d96801e638778b0ae9d58b4082cb757e
Date: Fri, 29 Jun 2018 06:08:38 GMT
Expires: Fri, 29 Jun 2018 06:08:00 GMT

Android 获取方式:

 private void getNetTime() {
URL url = null;//取得资源对象
try {
url = new URL("http://www.baidu.com");
//url = new URL("http://www.ntsc.ac.cn");//中国科学院国家授时中心
//url = new URL("http://www.bjtime.cn");
URLConnection uc = url.openConnection();//生成连接对象
uc.connect(); //发出连接
long ld = uc.getDate(); //取得网站日期时间
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(ld);
final String format = formatter.format(calendar.getTime());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "当前网络时间为: \n" + format, Toast.LENGTH_SHORT).show();
tvNetTime.setText("当前网络时间为: \n" + format);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}

详情:Android - 获取系统时间和网络时间

2、NTP客户端访问NTP服务器

NTP(Network Time Protocol)是用来使计算机时间同步化的一种协议,它可以使计算机对其服务器或时钟源(如石英钟,GPS等等)做同步化,它可以提供高精准度的时间校正(LAN上与标准间差小于1毫秒,WAN上几十毫秒),且可介由加密确认的方式来防止恶毒的协议攻击。

// NTP server list: http://tf.nist.gov/tf-cgi/servers.cgi
// NTP server list: http://www.ntp.org.cn/pool.php
public static final String TIME_SERVER = "time-a.nist.gov"; public static long getCurrentNetworkTime() {
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
//long localDeviceTime = timeInfo.getReturnTime();
long serverTime = timeInfo.getMessage().getTransmitTimeStamp().getTime(); Date time = new Date(serverTime);
Log.d(TAG, "Time from " + TIME_SERVER + ": " + time); return serverTime;
}

详情:Get Network Time

最新文章

  1. “老坛泡新菜”:SOD MVVM框架,让WinForms焕发新春
  2. 通过配置web.config使WCF向外提供HTTPS的Restful Service
  3. [HIMCM暑期班]第1课:概述
  4. SQLServer日期格式化
  5. 第七天:JS内置对象-String字符串对象
  6. ipa上传到APP store
  7. 【前端学习】【CSS选择器】
  8. ServletContext对象--三大域对象
  9. Html.Action和Html.RederAction来创建子视图
  10. toj4119HDFS
  11. 状态压缩DP------学习小记
  12. url路径
  13. 淘淘商城_day06_课堂笔记
  14. Suzuki EN3F 参数
  15. hdoj1072 Nightmare bfs
  16. 201521123030 《Java程序设计》 第13周学习总结
  17. SpringBoot 整合Ehcache3
  18. [angularjs] 前端路由实现单页跳转
  19. 前后端分离djangorestframework——版本控制组件
  20. CrawlSpiders模块的使用

热门文章

  1. macos npm + node 环境启动问题排查
  2. Java中<? extends T>和<? super T>的理解
  3. OPERQUERY查询,关于效率,或者说正确用法
  4. Kbengine游戏引擎-【5】用Dockerfile打包镜像kbengine
  5. Grafana添加Zabbix为数据源(一)
  6. H5和原生APP之间的区别
  7. unix进程间通信方式(下)-unix域套接字(转)
  8. Kafka API使用
  9. nodeslector使用
  10. 硬盘相关合集,以及LVM操作实践