import java.time.*; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; import java.util.Formatter; import static java.time.temporal.TemporalAdjusters.lastDayOfMonth; import static java.time.temporal.TemporalAdjusters.nextOrSame; public class TimeDemo { public static void main(String[] args) { LocalDate date = LocalDate.of(2014,3,18); int year = date.getYear(); Month month = date.getMonth(); int day = date.getDayOfMonth(); DayOfWeek dow = date.getDayOfWeek(); int len = date.lengthOfMonth(); boolean leap = date.isLeapYear(); LocalDate today = LocalDate.now(); LocalDateTime time = LocalDateTime.of(2018,4,12,12,12); System.out.println(time); System.out.println(date); System.out.println(year); System.out.println(month); System.out.println(day); System.out.println(dow); System.out.println(len); System.out.println(leap); System.out.println(today); //获取时长 Period tenDays = Period.between(LocalDate.of(2014, 3, 8), LocalDate.of(2014, 3, 18)); System.out.println(tenDays.getDays()); System.out.println(tenDays.getMonths()); //Duration 和 Period对象 Duration threeMinutes = Duration.ofMinutes(3); Duration threeMinutes2 = Duration.of(3, ChronoUnit.MINUTES); Period tenDays2 = Period.ofDays(10); Period threeWeeks = Period.ofWeeks(3); Period twoYearsSixMonthsOneDay = Period.of(2, 6, 1); System.out.println(threeMinutes.getSeconds()); System.out.println(threeMinutes2.getSeconds()); System.out.println(tenDays2.getDays()); System.out.println(threeWeeks.getDays()); System.out.println(twoYearsSixMonthsOneDay.getDays()); //操纵、解析、格式化日期 LocalDate date11 = LocalDate.of(2014, 3, 18); LocalDate date21 = date11.withYear(2011); LocalDate date31 = date21.withDayOfMonth(25); LocalDate date41 = date31.with(ChronoField.MONTH_OF_YEAR, 9); System.out.println(date11); System.out.println(date21); System.out.println(date31); System.out.println("---"+date41); //以相对方式修改LocalDate对象的属性 LocalDate date12 = LocalDate.of(2014, 3, 18); LocalDate date22 = date12.plusWeeks(1); LocalDate date32 = date22.minusYears(3); LocalDate date42 = date32.plus(6, ChronoUnit.MONTHS); System.out.println(date12); System.out.println(date22); System.out.println(date32); System.out.println(date42); //使用 TemporalAdjuster LocalDate date13 = LocalDate.of(2014, 3, 18); LocalDate date23 = date13.with(nextOrSame(DayOfWeek.SUNDAY)); LocalDate date33 = date13.with(lastDayOfMonth()); System.out.println("----------"); System.out.println(date13); System.out.println(date23); System.out.println(date33); } }
Java8 时间格式化新方案
最新推荐文章于 2024-08-16 15:39:17 发布