时间无非也就分两种了, 系统时间,网络时间。
系统时间
System.currentTimeMillis()
由java语言提供,计算从1970年1月1号0时0分0秒到当前系统所设定的时间的差值,
SystemClock.elapsedRealtime()
由android APi提供,计算从手机boot到当前时间的差值。
规范显示
上述两种方法只是得到了差值却不能清晰得到明确时间。
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = new Date(System.currentTimeMillis());
String strTime = simpleDateFormat.format(date);
Date类将差值转换成具体的年月日等等,然后通过SimpleDateFormat类提供规范的表达。
如果要分别得到这些时间单位可以通过 Calendar这个类。
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int year = calendar.get(Calendar.YEAR);
int monday = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int dayWeek = calendar.get(Calendar.DAY_OF_WEEK);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
if (dayWeek == calendar.MONDAY) {
}
if (dayWeek == calendar.TUESDAY) {
}
if (dayWeek == calendar.WEDNESDAY) {
}
if (dayWeek == calendar.THURSDAY) {
}
if (dayWeek == calendar.FRIDAY) {
}
if (dayWeek == calendar.SATURDAY) {
}
if (dayWeek == calendar.SUNDAY) {
}
先得到Calendar实例,传入时间差值,最后得到具体时间即可。
网络时间
一般当我们修正时间都是从网络获取的,其实原理很简单,从服务器的响应头中获取时间值就ok了,当然这里的服务器大型的靠谱, 以百度为例。
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder().url("https://www.baidu.com").build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String strDate = response.header("date");
Date date = new Date(Date.parse(strDate));
String strReadAble = simpleDateFormat.format(date);
}
});
向百度发一个请求,从响应头里得到Key为”date”的Values然后解析即可。提示Date.parse方法已弃用,但是新方法在这一步报错,不知什么情况。