获取本地日期与时间
public String getCalendar() { @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date dt = new Date(); return sdf.format(dt); } //SimpleDateFormat 时间格式 //y 年 MM 月 dd 日 //D 一年的第几天 W 一个月的第几星期 w 一年的第几星期 k时 z时区 //HH 小时(24小时制) hh小时(12小时制) mm 分 ss 秒 SS 毫秒 E 星期 //a 上午/下午
计算相隔天数
/** * 获得天数差 * @param begin * @param end * @return */ public long getDayDiff(Date begin, Date end){ long day = 1; if(end.getTime() < begin.getTime()){ day = -1; }else if(end.getTime() == begin.getTime()){ day = 1; }else { day += (end.getTime() - begin.getTime())/(24 * 60 * 60 * 1000) ; } return day-1; } Date date=new Date(2017-1900,11,1,0,30); Date date2=new Date(2018-1900,11,1,0,30); getDayDiff(date,date2)
计算时间差
public static String getTimeDiffer(String date,String date2,String str){ long diff,days,hours,minutes; @SuppressLint("SimpleDateFormat") DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); try { Date d1 = df.parse(date); Date d2 = df.parse(date2); if(d1.getTime()>d2.getTime()) { diff = d1.getTime() - d2.getTime();//这样得到的差值是毫秒级别 days = diff / (1000 * 60 * 60 * 24); hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60); minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60); }else{ return "已到期"; } if(days==0){ if(hours==0){ return minutes+"分钟"; } } if(str.equals("精确")){ return ""+days+"天"+hours+"小时"+minutes+"分钟"; } return ""+days+"天"+hours+"小时"; }catch (Exception ignored){ } return ""; }
判断日期是否在指定日期
public static int getTimeCompareSize2(String startTime, String endTime){ int i=0; @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");//年-月-日 时-分 try { Date date1 = dateFormat.parse(startTime);//开始时间 Date date2 = dateFormat.parse(endTime);//结束时间 if (date2.getTime()<date1.getTime()){ i= 1;// 结束时间小于开始时间 }else if (date2.getTime()==date1.getTime()){ i= 2;//开始时间与结束时间相同 }else if (date2.getTime()>date1.getTime()){ i= 3;//结束时间大于开始时间 } } catch (ParseException e) { e.printStackTrace(); } return i; }
获取网络时间与日期
private void getNetTime() { URL url = null; try { url = new URL("http://www.baidu.com"); URLConnection uc = url.openConnection(); uc.connect(); long ld = uc.getDate(); //取得网站日期时间 @SuppressLint("SimpleDateFormat") DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(ld); final String format = formatter.format(calendar.getTime()); boottom_tiem.setText(format); } catch (Exception e) { e.printStackTrace(); } }