转载自lijiao
项目开发中,很多时候会用到android的时间,罗列一下获取的时间的方式,和大家共同学习进步
一、获取系统时间
1.通过Calendar类来获取系统当前的时间
1
2
3
4
5
6
7
8
9
10
|
Calendar calendar = Calendar.getInstance();
long
unixTime = calendar.getTimeInMillis();
//这是时间戳
Logger.i(TAG,
"calendar--->>>"
+
"当前时间为:"
+ calendar.get(Calendar.YEAR) +
"年 "
+ calendar.get(Calendar.MONTH) +
"月 "
+ calendar.get(Calendar.DAY_OF_MONTH) +
"日 "
+ calendar.get(Calendar.HOUR_OF_DAY) +
"时 "
+ calendar.get(Calendar.MINUTE) +
"分 "
+ calendar.get(Calendar.SECOND) +
"秒"
);
|
打印结果如下:
calendar--->>>当前时间为:2016年 6月 13日 14时 38分 58秒
2.通过Time来获取,android的文档中说使用Time比Calendar对CPU的性能损耗更小,我却不推荐使用Time,因为Time使用必须在24小时制的系统中,如果用户手机就设成12小时制的,这时就有误差
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
Time times =
new
Time(
"GMT+8"
);
/*对于已经设定为GMT时间标准的dateFormat来说,
一切需要他转换的字符串日期都是GMT标准时间,
转换后返回的Date由于默认
*遵守系统默认时区,所以转换给Date的日期需要+8
(例如北京标准时区),也就是时区与标准不同导致的时差。*/
times.setToNow();
int
year = times.year;
int
month = times.month;
int
day = times.monthDay;
int
minute = times.minute;
int
hour = times.hour;
int
sec = times.second;
Logger.i(TAG,
"当前时间为:"
+ year +
"年 "
+ month +
"月 "
+ day +
"日 "
+ hour +
"时 "
+ minute +
"分 "
+ sec +
"秒"
);
|
打印结果:当前时间为:2016年 6月 13日 6时 38分 58秒
注意:这时的时间和上面使用时间是同一时间,不过时间我都调成是12小时制的
当然,还有其他的获取方式,不过结果基本都一样
1
2
3
4
5
|
import
java.text.SimpleDateFormat;
SimpleDateFormat formatter =
new
SimpleDateFormat (
"yyyy年MM月dd日 HH:mm:ss"
);
Date curDate =
new
Date(System.currentTimeMillis());
String str = formatter.format(curDate);
|
还有
1
2
|
DateFormat df =
new
SimpleDateFormat(
"HH:mm:ss"
);
df.format(
new
Date());
|
二、获取网络时间
很多时候,由于手机的不确定性,导致各个手机的时间都不尽相同,如果开发中需要获取统一的时间来匹配一些规则的时候,比如我之前公司就是通过或去当前时间并且转换之后来匹配网络连接的规则,防止大批量的抓包,那么这个时候就需要一个统一的时间和后台进行匹配,这是简单的使用获取系统时间就可能存在问题,用户手机如果调成自动获取网络时间的话没问题,但是如果不是呢?所以获取网络时间就派上了用处
1
2
3
4
5
6
7
8
9
10
|
URL url =
null
;
//取得资源对象
try
{
URLConnection uc = url.openConnection();
//生成连接对象
uc.connect();
//发出连接
ld = uc.getDate();
//取得网站日期时间
Logger.i(TAG,
"ld---->>>>"
+ld);
}
catch
(Exception e) {
e.printStackTrace();
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。