JDK8之LocalDate/LocalDateTime

LocalDate

java.util.Date相互转换:

Date today = new Date();
LocalDate localDate = today.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate now = LocalDate.now();
Date date = Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant());
//格式化
String format = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//日期计算

//增加一天
LocalDate plus2 = localDate.plusDays(1);
//减1天
LocalDate minus2 = localDate.minusDays(1);
//加1周
LocalDate plus3 = localDate.plusWeeks(1);
//减1周
LocalDate minus3 = localDate.minusWeeks(1);
//加1个月
LocalDate plus4 = localDate.plusMonths(1);
//减1个月
LocalDate minus4 = localDate.minusMonths(1);
//加1年
LocalDate plus5 = localDate.plusYears(1);
//减1年
LocalDate minus5 = localDate.minusYears(1);
//加1年
LocalDate plusYears = localDate.plus(1, ChronoUnit.YEARS);
//加1个月
LocalDate plusMonths = localDate.plus(1, ChronoUnit.MONTHS);
//加1周
LocalDate plusWeeks = localDate.plus(1, ChronoUnit.WEEKS);
//加1天
LocalDate plusHalfDays = localDate.plus(1, ChronoUnit.DAYS);
//加半天
LocalDate plusDays = localDate.plus(1, ChronoUnit.HALF_DAYS);
//加1小时
LocalDate plusHours = localDate.plus(1, ChronoUnit.HOURS);
//加1分钟
LocalDate plusMinutes = localDate.plus(1, ChronoUnit.MINUTES);
//加1秒
LocalDate plusSeconds = localDate.plus(1, ChronoUnit.SECONDS);
//减少时间
LocalDate minusYears = localDate.minus(1, ChronoUnit.YEARS);
//指定日期
LocalDate withYear = localDate.withYear(2019);
LocalDate withMonth = localDate.withMonth(12);
LocalDate withDayOfMonth = localDate.withDayOfMonth(12);
LocalDate withDayOfYear = localDate.withDayOfYear(360);
LocalDate with = localDate.with(ChronoField.YEAR, 2018);
LocalDate with2 = localDate.with(ChronoField.MONTH_OF_YEAR, 12);
LocalDate with3 = localDate.with(ChronoField.DAY_OF_YEAR, 300);
LocalDate with4 = localDate.with(ChronoField.DAY_OF_MONTH, 21);
LocalDate with5 = localDate.with(ChronoField.DAY_OF_WEEK, 3);
LocalDate with6 = localDate.with(ChronoField.DAY_OF_MONTH, 20);
//获取日期
int year = localDate.getYear();
int monthValue = localDate.getMonthValue();
int dayOfMonth = localDate.getDayOfMonth();
int dayOfYear = localDate.getDayOfYear();
int dayOfWeek = localDate.getDayOfWeek().getValue();

int dayOfMonth2 = localDate.get(ChronoField.DAY_OF_MONTH);
//两个日期相差天数
long days = localDate.toEpochDay() - LocalDate.of(2019, 8, 10).toEpochDay();
......

//周
LocalDate now = LocalDate.now();
//获取某一周的周一的日期
LocalDate monday = now.with(DayOfWeek.MONDAY);

LocalDateTime

java.util.Date相互转换:

Date today = new Date();
LocalDateTime localDateTime = today.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
LocalDateTime now = LocalDateTime.now();
Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
//格式化
String format = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

常用方法:


你可能感兴趣的:(Java)