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);
}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值