1.获取两个Date之间的相差多少?(秒、分、时、天)
try{ SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); smdate=sdf.parse(sdf.format(smdate)); bdate=sdf.parse(sdf.format(bdate)); Calendar cal = Calendar.getInstance(); cal.setTime(smdate); long time1 = cal.getTimeInMillis(); cal.setTime(bdate); long time2 = cal.getTimeInMillis(); long between_minutes=(time2-time1)/(1000*60); Integer.parseInt(String.valueOf(between_minutes)); }catch (ParseException e){ e.printStackTrace(); }
2.获取一天中的最开始时间
try { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); current = sdf.parse(sdf.format(current)); Calendar calendar = Calendar.getInstance(); calendar.setTime(current); calendar.set(Calendar.HOUR_OF_DAY,0); calendar.set(Calendar.MINUTE,0); calendar.set(Calendar.SECOND,0); calendar.set(Calendar.MILLISECOND,0); Date dayStart = calendar.getTime(); return dayStart; } catch (ParseException e) { e.printStackTrace(); }
3.获取一天中的最结束时间
try { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); current = sdf.parse(sdf.format(current)); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY,23); calendar.set(Calendar.MINUTE,59); calendar.set(Calendar.SECOND,59); calendar.set(Calendar.MILLISECOND,999); Date dayEnd = calendar.getTime(); return dayEnd; } catch (ParseException e) { e.printStackTrace(); }
4. LocalDateTime 转Date
获取本月开始的时间(LocalDateTime)并转换成Date形式:
public static LocalDateTime getFirstDayOfMonth() { LocalDateTime date = LocalDateTime.now(); LocalDateTime firstday = date.with(TemporalAdjusters.firstDayOfMonth()); return LocalDateTime.of(firstday.toLocalDate(), LocalTime.MIN); } public static Date getDateByFirstDayOfMonth() { LocalDateTime minFirestDay = getFirstDayOfMonth(); ZoneId zoneId = ZoneId.systemDefault(); ZonedDateTime zdt = minFirestDay.atZone(zoneId); return Date.from(zdt.toInstant()); }
原文:https://www.cnblogs.com/zhangshitong/p/12640070.html