一、通过免费或者收费的API接口获取
1、免费
- QQ:http://cgi.im.qq.com/cgi-bin/cgi_svrtime
- 淘宝:http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp
- 苏宁:http://quan.suning.com/getSysTime.do
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, "当前网络时间为:
" + format, Toast.LENGTH_SHORT).show();
tvNetTime.setText("当前网络时间为:
" + format);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
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;
}