当前项目中用到的时间计算比较多,在此记录,以便查用
实现再点一次退出程序
private long exitTime = 0;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exit();
return false;
}
return super.onKeyDown(keyCode, event);
}
public void exit() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
showMessage("再按一次退出程序");
exitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0);
}
}
去掉年月日
public static String time(String time) {
String str = "";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
Date dt1 = df.parse(time);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
str = sdf.format(dt1);
// mTvTime.setText(str);
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
比较两个时间的先后顺序
//type 为要转成的类型 exapmle: "yyyy-MM-dd HH:mm:ss"
public static boolean compare_date(String DATE1, String DATE2,String type) {
boolean s = true;
// "HH:mm"
DateFormat df = new SimpleDateFormat(type);
Date dt1;
Date dt2;
try {
dt1 = df.parse(DATE1);
dt2 = df.parse(DATE2);
s = dt1.before(dt2);
} catch (Exception exception) {
exception.printStackTrace();
}
return s;
}
计算两个时间 差
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
Date d1 = df.parse(starttime());
Date d2 = df.parse(endtime());
long diff = d2.getTime() - d1.getTime();//这样得到的差值是微秒级别
long days = diff / (1000 * 60 * 60 * 24);
long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
// System.out.println("" + days + "天" + hours + "小时" + minutes + "分");
text.setText("请假天数:" + days + "天" + hours + "小时" + minutes + "分");
} catch (Exception e) {
e.printStackTrace();
}