温馨提示×

java中localdatetime的用法是什么

小亿
85
2024-01-09 16:28:43
栏目: 编程语言

LocalDateTime是Java 8中引入的日期时间类,用于表示一个不可修改的日期时间对象,不包含时区信息。

LocalDateTime类的用法如下:

  1. 创建LocalDateTime对象:

    LocalDateTime now = LocalDateTime.now();  // 获取当前日期时间
    LocalDateTime specificDateTime = LocalDateTime.of(2021, 12, 31, 23, 59, 59); // 创建指定日期时间
    LocalDateTime parsedDateTime = LocalDateTime.parse("2021-12-31T23:59:59"); // 解析字符串为日期时间
    
  2. 获取日期时间的各个部分:

    int year = now.getYear();
    Month month = now.getMonth();
    int dayOfMonth = now.getDayOfMonth();
    int hour = now.getHour();
    int minute = now.getMinute();
    int second = now.getSecond();
    
  3. 修改日期时间的各个部分:

    LocalDateTime modifiedDateTime = now.withYear(2022).withMonth(1).withDayOfMonth(1); // 修改年、月、日
    LocalDateTime plusDateTime = now.plusDays(1).plusHours(2); // 增加1天2小时
    LocalDateTime minusDateTime = now.minusMonths(1).minusMinutes(30); // 减去1个月30分钟
    
  4. 比较日期时间的先后关系:

    boolean isAfter = now.isAfter(specificDateTime); // 判断是否在指定日期时间之后
    boolean isBefore = now.isBefore(specificDateTime); // 判断是否在指定日期时间之前
    
  5. 格式化日期时间为字符串:

    String formattedDateTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); // 格式化为指定格式的字符串
    
  6. 其他常用方法:

    LocalDateTime truncatedDateTime = now.truncatedTo(ChronoUnit.HOURS); // 截断到小时
    LocalDateTime startOfDay = now.toLocalDate().atStartOfDay(); // 获取当天的开始时间
    

注意:LocalDateTime类是不可变的,任何修改操作都会返回一个新的对象。

0