一.使用Calendar获取系统时间
Calendar获取系统时间首先要用Calendar.getInstance()函数获取一个实例,再为该实例设定时区(中国的时区为GMT+8:00),最后使用Calendar.get()函数获取时间的具体信息,如年,月,日,小时,分,秒,星期几。
缺点是获得的这些时间信息都是独立的,如果要一起显示的话,还要组装起来凑成一个字符串,稍显麻烦。不过如果只需要单个时间信息,如星期几,这种方法是比较方便的。并且可以根据Calendar.AMPM属性判断当前是AM还是PM(0为AM,1为PM),然后根据需要显示12小时或24小时的时间。或者直接获得Calendar.HOUROF_DAY显示24小时的时间。
Calendar calendars;
private void getTime4() {
calendars = Calendar.getInstance();
calendars.setTimeZone(TimeZone.getTimeZone(“GMT+8:00”));
String year = String.valueOf(calendars.get(Calendar.YEAR));
String month = String.valueOf(calendars.get(Calendar.MONTH));
String day = String.valueOf(calendars.get(Calendar.DATE));
String hour = String.valueOf(calendars.get(Calendar.HOUR));
String min = String.valueOf(calendars.get(Calendar.MINUTE));
String second = String.valueOf(calendars.get(Calendar.SECOND));
Boolean isAm = calendars.get(Calendar.AM_PM)==1 ? true:false;
Boolean is24 = DateFormat.is24HourFormat(getApplication()) ?true:false;
Log.i(“md”, " 年:"+year+" 月: “+month+” 日:"+day+" 时: “+hour+” 分: “+min+” 秒: “+second +” 是上午吗? “+isAm+” 是24小时制吗? "+is24);
}
二.使用date获取系统时间
Date方法比较简单,只需要一条语句:Date().toLocaleString(),就可以获得整个的时间信息,并且格式规范,不用再组装,可以直接显示。缺点是如果想用另外一种格式显示,或者只需要单个的时间信息,就比较麻烦。可以定义SimpleDateFormat,规定哪些信息显示,哪些信息不显示,如显示年、月、日、小时、分钟、星期几,可以定义下面的SimpleDateFormat:
Date date = new Date();
String time = date.toLocaleString();
Log.i(“md”, "时间time为: "+time);
SimpleDateFormat dateFormat = new SimpleDateFormat(“yyyy年-MM月dd日-HH时mm分ss秒 E”);
String sim = dateFormat.format(date);
Log.i(“md”, "时间sim为: "+sim);
三.使用currentTimeMills获取系统时间
1秒=1000毫秒(ms) 1毫秒=1/1,000秒(s)
1秒=1,000,000 微秒(μs) 1微秒=1/1,000,000秒(s)
1秒=1,000,000,000 纳秒(ns) 1纳秒=1/1,000,000,000秒(s)
1秒=1,000,000,000,000 皮秒(ps) 1皮秒=1/1,000,000,000,000秒(s)
1小时=60分钟=3600秒
long currentTime = System.currentTimeMillis();
SimpleDateFormat formatter = new SimpleDateFormat(“yyyy年-MM月dd日-HH时mm分ss秒”);
Date date = new Date(totalMillisecounds);
String sim = formatter.format(date);
Log.i(“md”, “当前时间:” +sim);
Android的获取系统时间
最新推荐文章于 2023-10-31 19:53:43 发布