1.在开发的时候,因为本机时间有时不准确,而往往会有需要取精准的网络时间的情况,该方法可以用来获取网络时间
/**
* 获取网络时间
* @param context context
* @return 网络时间
*/
public static DategetNetTime(Context context){
// String webUrl = "http://www.ntsc.ac.cn";//中国科学院国家授时中心
String webUrl ="http://www.baidu.com/";//百度
try {
URL url =new URL(webUrl);
URLConnection uc = url.openConnection();
uc.setReadTimeout(5000);
uc.setConnectTimeout(5000);
uc.connect();
long correctTime = uc.getDate();
Date date =new Date(correctTime);
return date;
}catch (Exception e) {
return new Date();
}
}
//将时间转换成String类型
SimpleDateFormat dateFormat=new SimpleDateFormat("YYYY-MM-dd HH:mm");
String format = dateFormat.format(date);
//将时间转换为时间戳
long time1 = date.getTime();
String s = String.valueOf(time1);