Android时间相关操作

来源:互联网 发布:货车软件有哪些 编辑:程序博客网 时间:2024/05/17 20:27

获取当前时间(完整格式)

  • 方法一(android.text.format.Time)
StringBuffer time = new StringBuffer();Time mTime = new Time("GMT+8");mTime.setToNow();time.append(mTime.year).append("-");time.append(mTime.month < 9 ? "0" : "").append(mTime.month + 1).append("-");time.append(mTime.monthDay < 9 ? "0" : "").append(mTime.monthDay).append(" ");time.append(mTime.hour).append(":");time.append(mTime.minute).append(":");time.append(mTime.second);System.out.println(time.toString());
  • 方法二(java.util.Date)
long millisecond = System.currentTimeMillis();SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date = new Date(millisecond);String time = format.format(date);System.out.println(time);
  • 方法三(java.util.Date)
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  String time=format.format(new Date());  System.out.println(time);
  • 方法四(java.util.Calendar)
StringBuffer time = new StringBuffer();Calendar calendar = Calendar.getInstance();time.append(calendar.get(Calendar.YEAR)).append("-");time.append(calendar.get(Calendar.MONTH) < 9 ? "0" : "").append(calendar.get(Calendar.MONTH) + 1).append("-");time.append(calendar.get(Calendar.DAY_OF_MONTH) < 9 ? "0" : "").append(calendar.get(Calendar.DAY_OF_MONTH)).append(" ");time.append(calendar.get(Calendar.HOUR_OF_DAY)).append(":");time.append(calendar.get(Calendar.MINUTE)).append(":");time.append(calendar.get(Calendar.SECOND));System.out.println(time.toString());

获取当前时间戳

我们所使用到的时间戳一般为“Unix时间戳”,Unix时间戳是一种时间表示方式,定义为从格林威治时间1970年01月01日08时00分00秒起至现在的总秒数。

  • 方法一(java.lang.System)
long timestamp = 0;timestamp = System.currentTimeMillis() / 1000;System.out.println(timestamp);
  • 方法二(java.util.Date)
long timestamp = 0;timestamp = new Date().getTime() / 1000;System.out.println(timestamp);
  • 方法三(java.util.Calendar)
long timestamp = 0;timestamp = Calendar.getInstance().getTimeInMillis() / 1000;System.out.println(timestamp);

时间戳转换

  • 时间戳转换为具体时间
String time = null;SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");long timestamp = Long.valueOf("1470813903");time = format.format(new Date(timestamp * 1000));System.out.println(time);
  • 具体时间转换为时间戳
String timestamp = null;SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date = format.parse("2016-08-10 15:25:03");long milliscond = date.getTime();timestamp = String.valueOf(milliscond / 1000);System.out.println(timestamp);

计算时间间隔

long beginTime = Long.parseLong("1470813903");long endTime = Long.parseLong("1490813903");long second = endTime - beginTime;long minute = second / 60;long hour = minute / 60;long day = hour / 24;if (day > 0) {    System.out.println("相差" + day + "天");} else if (hour > 0) {    System.out.println("相差" + hour + "小时");} else if (minute > 0) {    System.out.println("相差" + minute + "分钟");} else if (second > 0) {    System.out.println("相差" + second + "秒");} else {    System.out.println("时间相同");}
0 0
原创粉丝点击