Java中日期之Date
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()); }
5.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate.now().format(dtf)
6.LocalDate的常见用法:获取当前日期、获取指定日期、指定日期月最后一天、指定日期月有多少天:
7.LocalDateTime指定日期格式,以及日期的相减:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String s = LocalDateTime.now().minusDays(1).format(dtf);
当前日期:2020-07-20 14:33:18
上述结果输出为:2020-07-19 14:28:18