Java.time常见使用
小知识
- LocalDateTime:
java.time.LocalDateTime
类表示ISO-8601
日历系统中没有时区的日期时间,例如2007-12-03T10:15:30
。表示与时区无关的日期和时间信息,不直接对应时刻,需要通过时区转换.
- Instant:
java.time.Instant
类在时间线上模拟单个瞬时点。不直接对应年月日信息,需要通过时区转换.
- LocalDate:
java.time.LocalDate
类表示ISO-8601
日历系统中没有时区的日期,例如:2007-12-03
表示与时区无关的日期,与LocalDateTime相比,只有日期信息,没有时间信息.
- LocalTime:
java.time.LocalTime
类表示ISO-8601
日历系统中没有时区的时间,例如10:15:30
表示与时区无关的时间,与LocalDateTime相比,只有时间信息,没有日期信息.
- ZonedDateTime:
java.time.ZonedDateTime
类表示ISO-8601
日历系统中具有时区的日期时间,例如:2007-12-03T10:15:30+01:00 Europe/Paris
.表示特定时区的日期和时间.
- ZoneId/ZoneOffset:时区.
LocalDate
LocalDate todayDate = LocalDate.now();System.out.println("获取今天的日期:" + todayDate);LocalDate targetDay = LocalDate.of(2099, 12, 12);System.out.println("获取指定的日期:" + targetDay);System.out.println("格式化:" + targetDay.format(DateTimeFormatter.BASIC_ISO_DATE));LocalDate feb = LocalDate.of(2099, 8, 12);System.out.println(feb.withYear(2019));System.out.println(feb.withDayOfYear(10));System.out.println(feb.withDayOfMonth(10));LocalDate stringDate = LocalDate.parse("20990202",DateTimeFormatter.BASIC_ISO_DATE);System.out.println("从标准格式的字符串获取日期:" + stringDate);System.err.println("不是标准的格式就会报错:" + LocalDate.parse("2099-2-2"));Period until = LocalDate.of(2021, 4, 22).until(LocalDate.of(2022, 8, 15));System.out.println(until);System.out.println(until.get(ChronoUnit.YEARS));System.out.println(until.get(ChronoUnit.MONTHS));System.out.println(until.get(ChronoUnit.DAYS));LocalDate firstDayOfThisMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());System.out.println("获取当前月份的第一天:" + firstDayOfThisMonth);LocalDate secondDayOfThisMonth = LocalDate.now().withDayOfMonth(2);System.out.println("获取当前月份的第二天:" + secondDayOfThisMonth);LocalDate lastDayOfThisMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());System.out.println("获取当前月份的最后一天(不需要管该月有几天):" + lastDayOfThisMonth);LocalDate afterLastDayOfThisMonth = lastDayOfThisMonth.plusDays(1);System.out.println("获取当前月份最后一天的下一天:" + afterLastDayOfThisMonth);LocalDate firstMondayOf2099 = LocalDate.parse("2099-12-12").with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));System.out.println("获取2099年的第一个月的第一个星期一:" + firstMondayOf2099);boolean isLeapYear = LocalDate.now().isLeapYear();System.out.println("判断是闰年吗:"+ isLeapYear);
LocalTime
LocalTime now = LocalTime.now();System.out.println("获取当前时间,它是包含毫秒的:" + now);LocalTime nowWithoutNano = LocalTime.now().withNano(0);System.out.println("一般情况不需要毫秒:" + nowWithoutNano);LocalTime customTime = LocalTime.of(05, 20, 0);System.out.println("创建一个时间:" + customTime); LocalTime praseTime = LocalTime.parse("05:20:00");System.out.println("按照标准格式创建一个时间:" + praseTime);System.out.println("要按照标准格式来,不然报错。时间和日期不同,它有三种格式:1. " + LocalTime.parse("05:20")+ " 2. " + LocalTime.parse("05:20:20") + " 3. " + LocalTime.parse("05:20:20.123"));LocalTime nowTimePlus2Hour = LocalTime.now().plusHours(2);LocalTime nowTimePlus2Hour2 = LocalTime.now().plus(2, ChronoUnit.HOURS);System.out.println("时间增加2小时:" + nowTimePlus2Hour + " 《====》 " + nowTimePlus2Hour2);System.out.println(LocalTime.now().compareTo(LocalTime.now().plusHours(10)));
LocalDateTime
LocalDateTime localDateTime = LocalDateTime.now();LocalDateTime plusYearsResult = localDateTime.plusYears(2L);LocalDateTime plusMonthsResult = localDateTime.plusMonths(3L);LocalDateTime plusDaysResult = localDateTime.plusDays(7L);LocalDateTime plusHoursResult = localDateTime.plusHours(2L);LocalDateTime plusMinutesResult = localDateTime.plusMinutes(10L);LocalDateTime plusSecondsResult = localDateTime.plusSeconds(10L);System.out.println("当前时间是 : " + localDateTime + "\n"+ "当前时间加2年后为 : " + plusYearsResult + "\n"+ "当前时间加3个月后为 : " + plusMonthsResult + "\n"+ "当前时间加7日后为 : " + plusDaysResult + "\n"+ "当前时间加2小时后为 : " + plusHoursResult + "\n"+ "当前时间加10分钟后为 : " + plusMinutesResult + "\n"+ "当前时间加10秒后为 : " + plusSecondsResult + "\n");LocalDateTime nextMonth = localDateTime.plus(1, ChronoUnit.MONTHS);LocalDateTime nextYear = localDateTime.plus(1, ChronoUnit.YEARS);LocalDateTime nextWeek = localDateTime.plus(1, ChronoUnit.WEEKS);System.out.println("now : " + localDateTime + "\n"+ "nextYear : " + nextYear + "\n"+ "nextMonth : " + nextMonth + "\n"+ "nextWeek :" + nextWeek + "\n");LocalDateTime from = LocalDateTime.of(2017, Month.JANUARY, 1, 00, 0, 0); LocalDateTime to = LocalDateTime.of(2019, Month.SEPTEMBER, 12, 14, 28, 0); Duration duration = Duration.between(from, to); long days = duration.toDays(); long hours = duration.toHours(); long minutes = duration.toMinutes(); long seconds = duration.getSeconds(); long milliSeconds = duration.toMillis(); long nanoSeconds = duration.toNanos(); System.out.println(LocalDateTime.of(2021, Month.DECEMBER, 8, 10, 59, 59));System.out.println(to);System.out.println(days);DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");String date2Str = dateTimeFormatter.format(LocalDateTime.now());System.out.println(date2Str);DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");String temp = dtf1.format(LocalDateTime.now());LocalDateTime formatedDateTime = LocalDateTime.parse(temp, dtf1);System.out.println(formatedDateTime);System.out.println("---------long毫秒值转换为日期---------");DateTimeFormatter df= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");long timeMillis = System.currentTimeMillis();System.out.println(timeMillis);Instant instant = Instant.ofEpochMilli(timeMillis);System.out.println(instant);LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Shanghai"));System.out.println(localDateTime);String longToDateTime = df.format(localDateTime);System.out.println(longToDateTime);Instant start = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));System.out.println(start);
ZonedDateTime
Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();System.out.println(availableZoneIds.size());ZoneId defZoneId = ZoneId.systemDefault();System.out.println(defZoneId);ZoneId shanghaiZoneId = ZoneId.of("Asia/Shanghai");System.out.println(shanghaiZoneId);String shanghai = ZoneId.SHORT_IDS.get("CTT");System.out.println(shanghai);Map<String, String> map = ZoneId.SHORT_IDS;for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey()+"===="+entry.getValue());}ZonedDateTime.now();ZonedDateTime.of(2017, 1, 1, 12, 0, 0, 0, ZoneId.of("Asia/Shanghai"));System.out.println(ZonedDateTime.ofInstant(Instant.now(), ZoneId.of("UTC")));ZonedDateTime zonedDateTimeUTC = LocalDateTime.now().atZone(ZoneId.of("UTC"));System.out.println(zonedDateTimeUTC);ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("UTC"));ZonedDateTime zonedDateTime = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("Asia/Shanghai"));System.out.println(zonedDateTime);System.out.println(zonedDateTime.withZoneSameLocal(ZoneId.of("UTC")));System.out.println(zonedDateTime.withZoneSameInstant(ZoneId.of("UTC")));
Clock
Clock clock = Clock.systemUTC();System.out.println("Clock : " + clock.millis());Clock defaultClock = Clock.systemDefaultZone();System.out.println("Clock : " + defaultClock.millis());
时区转换的一个栗子
String dateTimeStr1 = "2021-05-05T22:48:52+0800";String dateTimeStr2 = "2021-05-05T22:48:52+0700";ZonedDateTime zonedDateTime1 =ZonedDateTime.parse(dateTimeStr1, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"));System.out.println(zonedDateTime1);ZonedDateTime zonedDateTime2 =ZonedDateTime.parse(dateTimeStr2, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"));System.out.println(zonedDateTime2);ZonedDateTime losAngelesZonedDateTime1 =zonedDateTime1.withZoneSameInstant(ZoneId.of("America/Los_Angeles"));System.out.println(losAngelesZonedDateTime1);ZonedDateTime losAngelesZonedDateTime2 =zonedDateTime2.withZoneSameInstant(ZoneId.of("America/Los_Angeles"));System.out.println(losAngelesZonedDateTime2);ZonedDateTime result = zonedDateTime1.withZoneSameLocal(ZoneId.of("Asia/Shanghai"));System.out.println(result);