Java8中新的时间和日期API

LocalDate

获取系统当时日期: LocalDate.now();;

LocalDate date = LocalDate.now();

使用TemporalField读取LocalDate的值

int year = date.get(ChronoField.YEAR);
int month = date.get(ChronoField.MONTH_OF_YEAR);
int day = date.get(ChronoField.DAY_OF_MONTH);

LocalTime

LocalTime time = LocalTime.of(12, 45, 11); //13:45:11
LocalTime hour = time.getHour();
LocalTime minute = time.getMinute();
LocalTime secound = time.getSecound();

LocalDateTime

LocalDateTime dt1 = LocalDateTime.of(2017, 9, 14, 11, 11, 11);// 2017-9-11 11:11:11
LocalDateTime dt2 = LocalDateTime.of(date, time);
LocalDateTime dt3 = LocalDateTime.atTime(13, 45, 20);
LocalDateTime dt4 = LocalDateTime.atDate(date);

Instant(时间戳)

Instant instant = Instant.now();

Duration和Period对象

Duration d1 = Duration.between(time1, time2);
Duration d2 = Duration.between(dateTime1, dateTime2);
Druation d3 = Duration.between(instant1, instant2);

Period与Duration有类似的API。
Duration类主要用于秒和纳秒衡量时间的长短
Period类以年、月或者日的格式对多个时间建模

操纵日期

LocalDate date1 = LocalDate.of(2017, 9, 14);
LocalDate date2 = date1.withYear(2018);
LocalDate date3 = date1.withDayOfMonth(28);
LocalDate date4 = date1.with(ChronoField.MONTH_OF_YEAR, 10);

日期格式化

LocalDate date1 = LocalDate.of(2017, 9, 18);
String s1 = date1.format(DateTimeFormatter.BASIC_ISO_DATE);//20170918
String s2 = date1.format(DateTimeFormatter.ISO_LOCAL_DATE);//2017-09-18

你可能感兴趣的:(Java8中新的时间和日期API)