在android开发时经常用到时间相关的东西,把最近使用的方法总结一下,以后用的时候方便一些
<span style="white-space:pre"> </span>//获取当前时间
SimpleDateFormat formatter = new SimpleDateFormat ("yyyy/MM/dd/hh/mm/ss");
Date curDate = new Date(System.currentTimeMillis());
String str = formatter.format(curDate);
System.out.println("小写h12小时制 "+str);
//获取当前时间
SimpleDateFormat formatter2 = new SimpleDateFormat ("yyyy/MM/dd/HH/mm/ss");
Date curDate2 = new Date(System.currentTimeMillis());
String str2 = formatter2.format(curDate2);
System.out.println("大写H 24小时制"+str2);
大写的H获取的是24小时制,小写的获取的是12小时制,格式可以根据自己的需要修改,把“/”换为自己需要的分隔符,也可以去掉hh/mm/ss只要日期。
获取昨天的日期
<span style="white-space:pre"> </span>//获取昨天日期
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
String yesterday = new SimpleDateFormat( "yyyy/MM/dd ").format(cal.getTime());
System.out.println(yesterday);
-1获得昨天的日期,加减需要的数值获得对应的日期。
获取两个时间的差值
<span style="white-space:pre"> </span>Date current=new Date();
time1 = current.getTime();
SimpleDateFormat sim=new SimpleDateFormat("yyyy/MM/dd/hh/mm/ss");
String str="2015/12/20/14/40/50";
try {
Date d=sim.parse(str);
time2 = d.getTime();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
day = (time1 - time2) / (24 * 60 * 60 * 1000);
long shi = (time1 - time2) % (24 * 60 * 60 * 1000)/ (60 * 60 * 1000);
long fen = (time1 - time2) % (24 * 60 * 60 * 1000)% (60 * 60 * 1000)/(60 * 1000);
System.out.println(day+"天");
System.out.println(shi+"时");
System.out.println(fen+"分");
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
int a = c.get(Calendar.DAY_OF_YEAR);
System.out.println(a);
System.out.println(year+":"+(month+2)+":"+day+":"+hour+":"+minute+":"+second);