时间Date and Time
基础概念
时间点Timestamp
我们同一时刻,都在同一个时间点
计算机用 milliseconds since January 1, 1970, 00:00:00 GMT
相对时间(时区化时间)
几点几分几秒
同一个时间点下,不同时区,是不同的时间
日期
哪年哪月哪日
日期基于时区,纽约的早上,北京的晚上
日期基于日历,阳历,阴历
旧版时间系统
获取当前时间戳
1System.out.println(System.currentTimeMillis());
获取当前时间
1 2 3 Date date = new Date();System.out.println(date);System.out.println(date.getTime());
获取当前时区小时
1 2 3 Calendar calendar = new GregorianCalendar();calendar.setTime(new Date());System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
切换时区
1 2 3 4 5 6 7 8 Calendar calendar = new GregorianCalendar();calendar.setTime(new Date()); calendar.setTimeZone(TimeZone.getTimeZone("GMT+08"));System.out.println(calendar.get(Calendar.HOUR_OF_DAY)); calendar.setTimeZone(TimeZone.getTimeZone("GMT-04"));System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
整体格式化
1 2 SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");System.out.println(format.format(new Date()));
新版时间系统
获取当前时间点
1 2Instant instant = Instant.now();System.out.println(instant);
获取当前时间
1 2ZonedDateTime now = ZonedDateTime.now();System.out.println(now);
切换时区
1 2 3 ZonedDateTime now = ZonedDateTime.now();now = now.withZoneSameInstant(ZoneId.of("Asia/Shanghai"));System.out.println(now);
获取时间部分
1 2ZonedDateTime now = ZonedDateTime.now();System.out.println(now.getHour());
时间计算
1 2 3 4 ZonedDateTime now = ZonedDateTime.now();now = now.withDayOfMonth(8);now = now.plusHours(10);System.out.println(now);
去时区概念
1 2 3LocalDateTime dateTime = LocalDateTime.now();LocalDate date = LocalDate.now();LocalTime time = LocalTime.now();
计算差值
1 2 3 4 5 6 ZonedDateTime now = ZonedDateTime.now();ZonedDateTime before = now.withDayOfMonth(8).plusHours(10);Duration duration = Duration.between(before, now);System.out.println(duration);Period period = Period.between(before.toLocalDate(), ZonedDateTime.now().toLocalDate());System.out.println(period);