欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android关于获取时间的记录(小结)

程序员文章站 2022-06-14 17:42:18
序 初涉江湖,还望海涵! 写点东西,纯粹是因为个人的记忆能力较弱,写些笔记罢了,若有错误还望雅正! 对android中的时间获取做个记录,以下为结果! 代码粘贴...

初涉江湖,还望海涵!
写点东西,纯粹是因为个人的记忆能力较弱,写些笔记罢了,若有错误还望雅正!

对android中的时间获取做个记录,以下为结果!

Android关于获取时间的记录(小结)

代码粘贴

public class mainactivity extends appcompatactivity {
 public static final string tag = "mainactivity";
 
 @requiresapi(api = build.version_codes.cupcake)
 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);
  //timestamp
  textview timestamp = findviewbyid(r.id.timestamp_show);
  timestamp.settext("timestamp:" + system.currenttimemillis());
  //date
  date date = new date();
  textview date_show = findviewbyid(r.id.date_show);
  date_show.settext("date:" + date.tostring());
  //calendar
  textview calendar_show = findviewbyid(r.id.calendar_show);
  calendar calendar = calendar.getinstance();
  int year = calendar.get(calendar.year);
  int month = calendar.get(calendar.month);
  int day = calendar.get(calendar.date);
  int hour = calendar.get(calendar.hour);
  int minute = calendar.get(calendar.minute);
  int second = calendar.get(calendar.second);
  string calendar_show_string = "calendar:" + year + "-" + month + "-" + day
    + " " + hour + ":" + minute + ":" + second;
  calendar_show.settext(calendar_show_string);
  //time
  textview time_show = findviewbyid(r.id.time_show);
  time time = new time();
  time.settonow();
  int time_year = time.year;
  int time_month = time.month;
  int time_day = time.monthday;
  int time_hour = time.hour;
  int time_minute = time.minute;
  int time_second = time.second;
  string time_show_string = "time:" + time_year + "-" + time_month + "-"
    + time_day + " " + time_hour + ":" + time_minute + ":" + time_second;
  time_show.settext(time_show_string);
  //simpledateformat
  textview simpledateformat_show = findviewbyid(r.id.simpledateformat_show);
  simpledateformat format = new simpledateformat("yyyy-mm-dd hh:mm:ss");
  string simpledateformat_tring = "simpledateformat:" + format.format(new date());
  simpledateformat_show.settext(simpledateformat_tring);
  log.d(tag, "oncreate: long的最大值:" + long.max_value);

 }

根据自己使用过的以及网上搜索得到的结果,整理记录了以下方法

1 timestamp
2 date
3 simpledateformat
4 calendar
5 time

1 timestamp

 //timestamp
 textview timestamp = findviewbyid(r.id.timestamp_show);
 timestamp.settext("timestamp:" + system.currenttimemillis());

timestamp,时间戳。

使用时调用system类的currenttimemillis()方法,该方法的描述是:

 /**
 * returns the current time in milliseconds. note that
 * while the unit of time of the return value is a millisecond,
 * the granularity of the value depends on the underlying
 * operating system and may be larger. for example, many
 * operating systems measure time in units of tens of
 * milliseconds.
 *
 * <p> see the description of the class <code>date</code> for
 * a discussion of slight discrepancies that may arise between
 * "computer time" and coordinated universal time (utc).
 *
 * @return the difference, measured in milliseconds, between
 *   the current time and midnight, january 1, 1970 utc.
 * @see  java.util.date
 */
 public static native long currenttimemillis();

可以看出,该方法返回的是long类型的结果,结果记录的是midnight, january 1, 1970 utc至今经过的毫秒数(milliseconds)。

system.currenttimemillis()是一个native方法,是一个c/c++方法,由系统测量时间戳并返回测量结果,根据注释描述,测量结果可能偏大,因为有些操作系统测量时间是以十毫秒为单位的,类date中讨论了关于系统时间和utc时间产生差异的原因,可自行观看!

note:

  • utc(coordinated universal time)是民用时间的标准,众所周知,地球围绕太阳公转一周的时间定义为一年,地球自转一周定义为一天。有科学报道说,地球漫长的公转中其实是在缓慢的接近太阳,不管是否属实,自转和公转会产生一些变化也是不可避免的,utc就是正确测量时间的规则,当测量到需要校正时间时,会以毫秒为单位进行调整,称之为闰秒(leap seconds),后面time会提到!
  • system.currenttimemillis()的返回结果是一个记录从1970开始的毫秒数的long型结果,最容易想到的是long是有范围区间的,如果有一天记录的毫秒数超出long的范围怎么办!所以我计算了以下,long的最大值为0x7fff,ffff,ffff,ffff,取整大约为922亿亿,一年算365天,不考虑闰年,一天246060*60毫秒一年取整大约18亿毫秒,922亿/18,大约为50亿年,考虑到太阳的寿命,貌似也有用尽的一天。。。。但是,那么长的时间,鬼知道会发展成什么样!

2 date

 //date
 date date = new date();
 textview date_show = findviewbyid(r.id.date_show);
 date_show.settext("date:" + date.tostring());

通过实例化date类获取date实例从而获取时间,简单通过tostring()打印结果

date类的注释特别描述了

日历记时中,一年定为365天,闰年多一天,这表明,时间并不总是一天246060*60毫秒,需要用闰年加一天来调整。在coordinated universal time (utc)的时间定义中,是通过闰秒(leap second)来调整时间的,并且总是在6月30日或12月31日,具体表现为该类对秒的限制在0 to 61,60和61发生在leap second时。

构造函数

 public date() {
  this(system.currenttimemillis());
 }
 
 public date(long date) {
  fasttime = date;
 }
 
 /**
  * @param year the year minus 1900.
  * @param month the month between 0-11.
  * @param date the day of the month between 1-31.
  * @param hrs  the hours between 0-23.
  * @param min  the minutes between 0-59.
  * @param sec  the seconds between 0-59.
  * @see  java.util.calendar
  * @deprecated as of jdk version 1.1,
  * replaced by <code>calendar.set(year + 1900, month, date,
  * hrs, min, sec)</code> or <code>gregoriancalendar(year + 1900,
  * month, date, hrs, min, sec)</code>.
  */
 @deprecated
 public date(int year, int month, int date, int hrs, int min, int sec) {
  int y = year + 1900;
  // month is 0-based. so we have to normalize month to support long.max_value.
  if (month >= 12) {
   y += month / 12;
   month %= 12;
  } else if (month < 0) {
   y += calendarutils.floordivide(month, 12);
   month = calendarutils.mod(month, 12);
  }
  basecalendar cal = getcalendarsystem(y);
  cdate = (basecalendar.date) cal.newcalendardate(timezone.getdefaultref());
  cdate.setnormalizeddate(y, month + 1, date).settimeofday(hrs, min, sec, 0);
  gettimeimpl();
  cdate = null;
 }

无参大date()直接把system.currenttimemillis()的时间戳返回给fasttime,另一个就是设定好年月日时分秒来创建对象,其中的设定是年是1900+参数year并且也对月份超出范围做出了处理,但是该构造方法已是@deprecated(弃用)了

date类中大部分的方法都已经弃用,要特别是单独获取年或者月等信息的方法,基本上都已经弃用,留下的有打印即tostring()和一些比较等功能性的方法

3 simpledateformat

 //simpledateformat
 textview simpledateformat_show = findviewbyid(r.id.simpledateformat_show);
 simpledateformat format = new simpledateformat("yyyy-mm-dd hh:mm:ss");
 string simpledateformat_tring = "simpledateformat:" + format.format(new date());
 simpledateformat_show.settext(simpledateformat_tring);

simpledateformat类的核心是text的formatting(格式化)和time的parsing(解析),simpledateformat()通过传入一个字符串来格式化需要的表现形式,样例中通过调用format()传入date无参对象,实际上是调用system.currenttimemillis()获取最基本的时间,simpledateformat类的作用是把传入的date类时间定制化封装,从而得到需要的结果。

note:
关于simpledateformat类,可以很*的定制表现形式,年月日时分秒,时间格式,ad/bc。。。

定制化所用字母的含义:

  • g => ad/bc(年份为负数时),1+
  • y => year,1+
  • y => week year,24+
  • m => month in year,1+
  • w => week in year,1+
  • w => week in month,1+
  • d => day in year,1+
  • d => day in month,1+
  • f => day of week in month,1+
  • e => day name in week,1+
  • u => day number of week(1 = monday, ..., 7 = sunday),24+
  • a => am/pm marker,1+
  • h => hour in day (0-23),1+
  • k => hour in day (1-24),1+
  • k => hour in am/pm (0-11),1+
  • h => hour in am/pm (1-12),1+
  • m => minute in hour,1+
  • s => second in minute,1+
  • s => millisecond,1+
  • z => time zone:general time zone,pst,gmt-08:00,1+
  • z => time zone:rfc 822 time zone,1+
  • x => time zone:iso 8601 time zone,1+

定制化使用"字符串",在该字符串中使用'字符'表示在年月日等数据外的部分,如分隔符

simpledateformat类的时间格式定制包括年月日等数据的表现形式,连接符,日期格式的描述,如time zone,am/pm,ad/bc。。。

simpledateformat类中存在的问题是线程同步

/**
 * date formats are not synchronized.
 * it is recommended to create separate format instances for each thread.
 * if multiple threads access a format concurrently, it must be synchronized
 * externally.
 */

simpledateformat是线程不同步的,要在多线程中使用则要在线程外同步.

4 calendar

 //calendar
 textview calendar_show = findviewbyid(r.id.calendar_show);
 calendar calendar = calendar.getinstance();
 int year = calendar.get(calendar.year);
 int month = calendar.get(calendar.month);
 int day = calendar.get(calendar.date);
 int hour = calendar.get(calendar.hour);
 int minute = calendar.get(calendar.minute);
 int second = calendar.get(calendar.second);
 string calendar_show_string = "calendar:" + year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
 calendar_show.settext(calendar_show_string);

calendar是一个抽象类通过其内定义的calendar.getinstance()静态方法实例化对象而该静态方法最终是通过返回一个new gregoriancalendar(zone, alocale)来实现初始化!

calendar类内部定义了关于时间需要用到的索引并用一个int数组存储相关数据

 public final static int era = 0;
 public final static int year = 1;
 public final static int month = 2;
 public final static int week_of_year = 3;
 ...
 @suppresswarnings("protectedfield")
 protected int fields[];

 public int get(int field)
 {
  complete();
  return internalget(field);
 }
 
  protected final int internalget(int field)
 {
  return fields[field];
 }

calendar类的简单实用就是通过调用get方法从数组中获取相应的数据

5 time

//time
 textview time_show = findviewbyid(r.id.time_show);
 time time = new time();
 time.settonow();
 int time_year = time.year;
 int time_month = time.month;
 int time_day = time.monthday;
 int time_hour = time.hour;
 int time_minute = time.minute;
 int time_second = time.second;
 string time_show_string = "time:" + time_year + "-" + time_month + "-" + time_day + " " + time_hour + ":" + time_minute + ":" + time_second;
 time_show.settext(time_show_string);

把这段代码打入到剪辑器,你会看到time这个类是弃用了的

官方的注释解释是这样的

/**
 * an alternative to the {@link java.util.calendar} and
 * {@link java.util.gregoriancalendar} classes. an instance of the time class represents
 * a moment in time, specified with second precision. it is modelled after
 * struct tm. this class is not thread-safe and does not consider leap seconds.
 */

可以看到,描述上说,这是线程不安全的类,同时也没有处理leap seconds(闰秒)的能力,还举出了几个例子。

虽然是弃用的方法,但是还是可以看看怎么使用time类的,简单地说,就是通过对象.变量的形式获取,也就是说,time不像calendar类那样使用数组存储数据,time就是通过创建public int 数据 的形式来保存数据,也就是这些数据都是public的

总的来说,获取数据的时候,通过time的形式,如int time_hour = time.hour;这样的写法,其实才是最舒服的(个人感觉),当然,最重要的还是安全问题

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。