@Tyhj
2017-04-18T15:05:20.000000Z
字数 1929
阅读 3030
Android
原文:https://www.zybuluo.com/Tyhj/note/727298
Android获取时间戳方式
//最快System.currentTimeMillis();//最慢Calendar.getInstance().getTimeInMillis();//很快,过时了new Date().getTime();
通过Date可以获取string
SimpleDateFormat format= new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");String str=format.format(date);
Android 获取当天时间和明天的时间
//获取当天时间public static String getNowTime(){String time;Date now = new Date();SimpleDateFormat df = new SimpleDateFormat("MM月dd日");time=df.format(now);return time;}//明天的时间public static String getNextTime(){String time;Date next = new Date();Calendar calendar = new GregorianCalendar();calendar.setTime(next);calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动next=calendar.getTime(); //这个时间就是日期往后推一天的结果SimpleDateFormat df = new SimpleDateFormat("MM月dd日");time=df.format(next);return time;}
一般从服务器获取到的时间戳数据为一个long或者string类型
//string转Datejava.util.Date date = df.parse(df.format(Long.parseLong(timeString)));//long转Datejava.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中为毫秒
String result = formatData("yyyy-MM-dd", 1414994617);public static String formatData(String dataFormat, long timeStamp) {if (timeStamp == 0) {return "";}timeStamp = timeStamp * 1000;SimpleDateFormat format = new SimpleDateFormat(dataFormat);String result = format.format(new Date(timeStamp));return result;}
关于倒计时,就是计算时间戳的差,得到毫秒,再除以单位,就是相差时间
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date now = new Date();long l,year,mouth,day, hour, min, s;try {java.util.Date date = df.parse(df.format(Long.parseLong(startTime)));l = now.getTime() - date.getTime();year=l/(365*24 * 60 * 60 * 1000);mouth=l/(30*24 * 60 * 60 * 1000)-year*12;day = l / (24 * 60 * 60 * 1000)-mouth*30;hour = (l / (60 * 60 * 1000) - day * 24);min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);} catch (Exception e) {e.printStackTrace();}
