上篇文章簡單介紹了Java8時(shí)間日期的基本使用,以及應(yīng)用場景分瘦。這篇文章重點(diǎn)介紹骄恶,實(shí)際項(xiàng)目中使用到的Java 8時(shí)間日期。
Date類型轉(zhuǎn)換為LocalDateTime
LocalDateTime startTime = LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault());
轉(zhuǎn)換的時(shí)候需要用到時(shí)區(qū)ZoneID, 它根據(jù)一定的規(guī)則將Instant轉(zhuǎn)換成一個(gè)LocalDateTime梅忌。
下面是一個(gè)實(shí)際使用案例:
LocalDateTime startTime = LocalDateTime.ofInstant(assignOnlineRoomRequest.getStartTime().toInstant(), ZoneId.systemDefault());
LocalDateTime endTime = LocalDateTime.ofInstant(assignOnlineRoomRequest.getEndTime().toInstant(), ZoneId.systemDefault());
Preconditions.checkArgument(startTime.getHour() >= 8, "會(huì)議開始時(shí)間不能早于8點(diǎn)");
Preconditions.checkArgument(startTime.getHour() <= 20, "會(huì)議開始時(shí)間不能晚于20點(diǎn)");
Preconditions.checkArgument(startTime.toLocalDate().equals(endTime.toLocalDate()), "會(huì)議開始時(shí)間和結(jié)束時(shí)間必須是同一天");
Preconditions.checkArgument(endTime.isAfter(startTime), "會(huì)議結(jié)束時(shí)間必須在開始時(shí)間之后");
Preconditions.checkArgument(LocalDateTime.now().isBefore(endTime), "會(huì)議結(jié)束時(shí)間必須晚于當(dāng)前時(shí)間");
LocalDateTime格式化
LocalDateTime格式化為:yyyy-MM-dd HH:mm:ss
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
formatter.format(LocalDateTime.now())
LocalDateTime的日期時(shí)間操作
LocalDateTime localDateTime = LocalDateTime.of(2020, Month.JULY, 1, 8, 0, 0);
//隨機(jī)往后偏移一個(gè)時(shí)間
LocalDateTime startTime =localDateTime.plusDays(RandomUtils.nextInt(1, 30)).plusHours(RandomUtils.nextInt(0, 12)).plusMinutes(RandomUtils.nextInt(0, 60)).plusSeconds(RandomUtils.nextInt(0, 60));
LocalDateTime endTime = startTime.plusMinutes(RandomUtils.nextInt(60, 180));
LocalDateTime轉(zhuǎn)換為Date類型
LocalDateTime now = LocalDateTime.now();
Instant instant = now.atZone(ZoneId.systemDefault()).toInstant();
Date date = Date.from(instant);
UTC時(shí)區(qū)字符串轉(zhuǎn)換為當(dāng)前時(shí)區(qū)時(shí)間
ZonedDateTime parse = ZonedDateTime.parse("2011-12-03T10:15:30Z").withZoneSameInstant(ZoneId.systemDefault());
LocalDateTime localDateTime = parse.toLocalDateTime();
System.out.println(localDateTime);
未完待續(xù)...