Android 获取系统时间、网络时间、时区时间

Android 获取网络时间、时区时间、同步时间

方法一:SimpleDateFormat  24小时制

SimpleDateFormat formart = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
formart.setTimeZone(TimeZone.getTimeZone("GMT+08"));  
String date = dff.format(new Date());

方法二:Calendar  非24小时制

Calendar calendar = Calendar.getInstance();

SimpleDateFormat formart = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");

formart.setTimeZone(TimeZone.getTimeZone("GMT+8"));

String time = sdf.format(calendar.getTime());

方法三: GregorianCalendar 

public static String getLocalDatetime(String local) {  
   Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone(local));  
   calendar.setTimeInMillis(Calendar.getInstance().getTimeInMillis());  
   String date = calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DAY_OF_MONTH);  
   String time = calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE) + ":" + calendar.get(Calendar.SECOND);  
   return date + " " + time;  
}

方法四:获取网络时间(http://www.bjtime.cn

// 取得 bjtime url
URL url = new URL("http://www.bjtime.cn");
// 生成 URLConnection对象
URLConnection connection = url.openConnection();
connection.connect(); 
// 取得网站日期时间
long date = connection.getDate(); 
// 转换为标准时间对象
Date date = new Date(date);
String dateTime = date.getHours()+":"+date.getMinutes()+":"+date.getSeconds());

方法五:获取本地(当地)时间 LocationManager

LocationManager manager = (LocationManager) this.getSystemService(MainActivity.LOCATION_SERVICE);
long networkTime = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getTime();
// 获取当前时间
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); 

// 当我们使用requestLocationUpdates时,我们需要实现LocationListener接口。
// 在LocationListen的回调onLocationChanged当中获取时间

@Override
public void onLocationChanged(Location location) {
    long time = location.getTime();
    Date date = new Date(time);
    Sring dateTime = time + " NETWORK_PROVIDER " + date);
}
发布了46 篇原创文章 · 获赞 74 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/MLQ8087/article/details/101300875