美文网首页
Java8 时间日期API

Java8 时间日期API

作者: Tinyspot | 来源:发表于2022-08-17 07:54 被阅读0次

1. 新日期API

  • 原时间API存在的问题:线程安全问题、设计混乱
  • 本地化日期API
    • java.time (JDK >= 1.8)
    • LocalData
    • LocalTime
    • LocalDateTime
    • Instant 时间戳
    • ZoneId 时区

1.1 新 API 特点

  • 严格区分日期、时间
    • Month 范围 1~12 (Jan ~ Dec)
    • Week 范围 1~7 (Mon ~ Sun)
    • 好处:不用考虑加1 减1 的问题
  • 不可变(类似String)

2. 实战

2.1 日期和时间

LocalDate date = LocalDate.now(); // 当前日期
LocalTime time = LocalTime.now(); // 当前时间
LocalDateTime dateTime = LocalDateTime.now(); // 当前日期和时间

指定日期和时间

LocalDate date = LocalDate.of(2022, 10, 30);
LocalTime time = LocalTime.of(15, 10, 20);
LocalDateTime dateTime = LocalDateTime.of(2022, 10, 30, 15, 10, 20);
LocalDateTime dateTime2 = LocalDateTime.of(date, time);

System.out.println(date + "," + time + "," + dateTime);
System.out.println(localDateTime + "; " + localDateTime.getYear() + "; " + localDateTime.getMonthValue());

2.2 LocalDateTime

  • 对日期和时间进行加减
    • plusDays()
    • minusHours()
    • plusWeeks()
  • 对日期和时间进行调整
    • withDayOfMonth()
    • withMonth()
    • withHour()
  • 判断日期和时间先后
    • isBefore()
    • isAfter()
    • equals()
public final class LocalDateTime implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable {
    public static LocalDateTime now() {
        return now(Clock.systemDefaultZone());
    }
    public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second) {
        LocalDate date = LocalDate.of(year, month, dayOfMonth);
        LocalTime time = LocalTime.of(hour, minute, second);
        return new LocalDateTime(date, time);
    }
}

对日期和时间进行加减

  LocalDateTime localDateTime = LocalDateTime.now();
  // 会产生新的对象
  LocalDateTime day = localDateTime.plusDays(2);
  // +2 月
  LocalDateTime months = localDateTime.minusMonths(2);
  // +1月 -2周
  localDateTime.plusMonths(1).minusWeeks(2);

对日期和时间进行调整

LocalDateTime localDateTime = LocalDateTime.now();
// 本月第1天
LocalDateTime firstDay = localDateTime.withDayOfMonth(1);
// 秒和纳秒调整为 0
LocalDateTime time = localDateTime.withSecond(0).withNano(0);

// 本月最后一天
LocalDateTime lastDay = localDateTime.with(TemporalAdjusters.lastDayOfMonth());
// 本月第1个周日
LocalDateTime firstSunday = localDateTime.with(TemporalAdjusters.firstInMonth(DayOfWeek.SUNDAY));
LocalDate date1 = LocalDate.of(2021, 1, 12);
LocalDate date2 = LocalDate.of(2022, 2, 10);
System.out.println(date1.isBefore(date2));

Period until = date1.until(date2);
System.out.println("时间差:" + until); // P1Y29D

2.3 Instant

  Instant instant = Instant.now();
  System.out.println(instant + "; " + instant.toEpochMilli());

  Instant instant2 = instant.plusSeconds(10);
  System.out.println("时间差:" + Duration.between(instant, instant2).toMillis());

2.4 ZonedDateTime 时区转换

  • ZoneId 表示时区
  • Instant 表示时刻(内部用 long 表示 epoch second)
  • ZonedDateTime 就是 LocalDateTime 关联 ZoneId
// 当前时区的日期和时间
ZonedDateTime zonedDateTime = ZonedDateTime.now();
// 纽约时区的日期
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/New_York"));
  // 获取所有时区
  Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
  availableZoneIds.forEach(System.out::println);
  System.out.println("当前时区:" + ZoneId.systemDefault());

LocalDateTime 转换

LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());

3. DateTimeFormatter

  • 原 DateFormat 抽象类,实现类 SimpleDateFormat 线程不安全,在多线程环境需要与 ThreadLocal 一起用
  • 不可变
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format = formatter.format(LocalDateTime.now());
System.out.println(format);

LocalDateTime dateTime = LocalDateTime.parse(format, formatter);
System.out.println(dateTime);

4. 时间互转

互转1: Date ----> Instant ----> LocalDateTime

Date date = new Date();
Instant instant = date.toInstant();
System.out.println(instant);

LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
System.out.println(localDateTime);

或者

Date date = new Date();
// Date --> LocalDate
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
// LocalDate result = localDate.plusDays(Long.parseLong(afterDays));
LocalDate afterDate = localDate.plusDays(2L);

Calendar 方式

Date date = new Date();
    Calendar calendar = Calendar.getInstance();//日历对象
    calendar.setTime(date);//设置当前日期
    calendar.add(Calendar.DATE, 3);//月份减一为-1,加一为1
    Date time = calendar.getTime();
    System.out.println(time);

互转2: LocalDateTime ----> Instant ----> Date

LocalDateTime localDateTime = LocalDateTime.now();
Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();

Date date = Date.from(instant);
System.out.println(date);

5. 新旧API

5.1 新旧 API 转换

long 类型作为中间态

5.2 Java 对象 - 数据库类型

数据库 Java类(旧) Java类(新)
DATETIME java.util.Date LocalDateTime
DATE java.sql.Date LocalDate
TIME java.sql.Time LocalTime
TIMESTAMP java.sql.Timestamp LocalDateTime

相关文章

网友评论

      本文标题:Java8 时间日期API

      本文链接:https://www.haomeiwen.com/subject/lpjdgrtx.html