[关闭]
@Tyhj 2017-04-18T15:05:20.000000Z 字数 1929 阅读 2669

关于时间戳,倒计时计算

Android


原文:https://www.zybuluo.com/Tyhj/note/727298

Android获取时间戳方式

  1. //最快
  2. System.currentTimeMillis();
  3. //最慢
  4. Calendar.getInstance().getTimeInMillis();
  5. //很快,过时了
  6. new Date().getTime();

通过Date可以获取string

  1. SimpleDateFormat format= new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
  2. String str=format.format(date);

Android 获取当天时间和明天的时间

  1. //获取当天时间
  2. public static String getNowTime(){
  3. String time;
  4. Date now = new Date();
  5. SimpleDateFormat df = new SimpleDateFormat("MM月dd日");
  6. time=df.format(now);
  7. return time;
  8. }
  9. //明天的时间
  10. public static String getNextTime(){
  11. String time;
  12. Date next = new Date();
  13. Calendar calendar = new GregorianCalendar();
  14. calendar.setTime(next);
  15. calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
  16. next=calendar.getTime(); //这个时间就是日期往后推一天的结果
  17. SimpleDateFormat df = new SimpleDateFormat("MM月dd日");
  18. time=df.format(next);
  19. return time;
  20. }

一般从服务器获取到的时间戳数据为一个long或者string类型

  1. //string转Date
  2. java.util.Date date = df.parse(df.format(Long.parseLong(timeString)));
  3. //long转Date
  4. java.util.Date date = df.parse(df.format(timeLong);

最常用的:
由于服务端返回的一般是UNIX时间戳,所以需要把UNIX时间戳timeStamp转换成固定格式的字符串

Unix时间戳(Unix timestamp),或称Unix时间(Unix time)、POSIX时间(POSIX time),是一种时间表示方法,定义为从格林威治时间1970年01月01日00时00分00秒起至现在的总秒数。Unix时间戳不仅被使用在Unix系统、类Unix系统中,也在许多其他操作系统中被广泛采用。Android中为毫秒

  1. String result = formatData("yyyy-MM-dd", 1414994617);
  2. public static String formatData(String dataFormat, long timeStamp) {
  3. if (timeStamp == 0) {
  4. return "";
  5. }
  6. timeStamp = timeStamp * 1000;
  7. SimpleDateFormat format = new SimpleDateFormat(dataFormat);
  8. String result = format.format(new Date(timeStamp));
  9. return result;
  10. }

关于倒计时,就是计算时间戳的差,得到毫秒,再除以单位,就是相差时间

  1. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  2. Date now = new Date();
  3. long l,year,mouth,day, hour, min, s;
  4. try {
  5. java.util.Date date = df.parse(df.format(Long.parseLong(startTime)));
  6. l = now.getTime() - date.getTime();
  7. year=l/(365*24 * 60 * 60 * 1000);
  8. mouth=l/(30*24 * 60 * 60 * 1000)-year*12;
  9. day = l / (24 * 60 * 60 * 1000)-mouth*30;
  10. hour = (l / (60 * 60 * 1000) - day * 24);
  11. min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
  12. s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
  13. } catch (Exception e) {
  14. e.printStackTrace();
  15. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注