LocalDateTime操作

  |   0 评论   |   19 浏览

1.LocalDateTime时间转换

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
​
public class DateTimeConversionExample {
    public static void main(String[] args) {
        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();
        
        // 方法1:使用预定义格式器
        DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        String isoString = now.format(isoFormatter);
        System.out.println("ISO格式: " + isoString);
        
        // 方法2:自定义格式
        DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String customString = now.format(customFormatter);
        System.out.println("自定义格式: " + customString);
        
        // 方法3:带本地化格式
        DateTimeFormatter localizedFormatter = DateTimeFormatter.ofPattern("EEEE, MMMM dd, yyyy hh:mm:ss a");
        String localizedString = now.format(localizedFormatter);
        System.out.println("本地化格式: " + localizedString);
        
        // 方法4:使用预定义常量
        DateTimeFormatter shortFormatter = DateTimeFormatter.ofLocalizedDateTime(
            java.time.format.FormatStyle.SHORT
        );
        String shortString = now.format(shortFormatter);
        System.out.println("短格式: " + shortString);
        
        // 方法5:带时区信息(转换为ZonedDateTime)
        String zonedString = now.atZone(java.time.ZoneId.systemDefault())
                               .format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
        System.out.println("带时区格式: " + zonedString);
    }
}
​

2.DateTimeUtils操作时间

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
​
public class DateTimeUtils {
​
    /**
     * 时间加法
     * @param baseTime 基准时间
     * @param amount 要添加的数量
     * @param unit 时间单位
     * @return 计算后的时间
     */
    public static LocalDateTime addTime(LocalDateTime baseTime, long amount, ChronoUnit unit) {
        return baseTime.plus(amount, unit);
    }
​
    /**
     * 时间减法
     * @param baseTime 基准时间
     * @param amount 要减去的数量
     * @param unit 时间单位
     * @return 计算后的时间
     */
    public static LocalDateTime subtractTime(LocalDateTime baseTime, long amount, ChronoUnit unit) {
        return baseTime.minus(amount, unit);
    }
​
    /**
     * 计算两个时间点之间的持续时间(毫秒)
     * @param start 开始时间
     * @param end 结束时间
     * @return 持续时间(毫秒)
     */
    public static long durationInMillis(LocalDateTime start, LocalDateTime end) {
        return Duration.between(start, end).toMillis();
    }
​
    /**
     * 计算两个时间点之间的持续时间(秒)
     * @param start 开始时间
     * @param end 结束时间
     * @return 持续时间(秒)
     */
    public static long durationInSeconds(LocalDateTime start, LocalDateTime end) {
        return Duration.between(start, end).getSeconds();
    }
​
    /**
     * 计算两个时间点之间的持续时间(分钟)
     * @param start 开始时间
     * @param end 结束时间
     * @return 持续时间(分钟)
     */
    public static long durationInMinutes(LocalDateTime start, LocalDateTime end) {
        return Duration.between(start, end).toMinutes();
    }
​
    /**
     * 计算两个时间点之间的持续时间(小时)
     * @param start 开始时间
     * @param end 结束时间
     * @return 持续时间(小时)
     */
    public static long durationInHours(LocalDateTime start, LocalDateTime end) {
        return Duration.between(start, end).toHours();
    }
​
    /**
     * 计算两个时间点之间的持续时间(天)
     * @param start 开始时间
     * @param end 结束时间
     * @return 持续时间(天)
     */
    public static long durationInDays(LocalDateTime start, LocalDateTime end) {
        return ChronoUnit.DAYS.between(start, end);
    }
​
    public static void main(String[] args) {
        // 当前时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前时间: " + now);
        
        // 加法示例
        LocalDateTime tomorrow = addTime(now, 1, ChronoUnit.DAYS);
        System.out.println("明天: " + tomorrow);
        
        LocalDateTime inTwoHours = addTime(now, 2, ChronoUnit.HOURS);
        System.out.println("两小时后: " + inTwoHours);
        
        // 减法示例
        LocalDateTime yesterday = subtractTime(now, 1, ChronoUnit.DAYS);
        System.out.println("昨天: " + yesterday);
        
        LocalDateTime thirtyMinutesAgo = subtractTime(now, 30, ChronoUnit.MINUTES);
        System.out.println("30分钟前: " + thirtyMinutesAgo);
        
        // 持续时间计算示例
        long millis = durationInMillis(thirtyMinutesAgo, now);
        System.out.println("30分钟持续时间(毫秒): " + millis);
        
        long minutes = durationInMinutes(thirtyMinutesAgo, now);
        System.out.println("30分钟持续时间(分钟): " + minutes);
        
        // 计算两个特定时间点的持续时间
        LocalDateTime startTime = LocalDateTime.of(2023, 1, 1, 8, 0);
        LocalDateTime endTime = LocalDateTime.of(2023, 1, 1, 10, 30);
        
        long hoursBetween = durationInHours(startTime, endTime);
        System.out.println("8:00到10:30之间的持续时间(小时): " + hoursBetween);
        
        long minutesBetween = durationInMinutes(startTime, endTime);
        System.out.println("8:00到10:30之间的持续时间(分钟): " + minutesBetween);
    }
}

3.完整LocalDateTime使用场景和用法

import java.time.*;
import java.time.format.*;
import java.time.temporal.*;
import java.util.concurrent.TimeUnit;
​
public class LocalDateTimeTest {
    public static void main(String[] args) {
        // 1. 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前时间: " + now);
​
        // 2. 创建指定日期时间
        LocalDateTime specificDate = LocalDateTime.of(2023, Month.OCTOBER, 15, 14, 30);
        System.out.println("指定日期时间: " + specificDate);
​
        // 3. 日期时间转字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        System.out.println("格式化日期时间: " + formattedDateTime);
​
        // 4. 字符串转日期时间
        String dateStr = "2023-12-25 08:30:00";
        LocalDateTime parsedDateTime = LocalDateTime.parse(dateStr, formatter);
        System.out.println("解析日期时间: " + parsedDateTime);
​
        // 5. 日期时间加减操作
        LocalDateTime tomorrow = now.plusDays(1);
        LocalDateTime lastWeek = now.minusWeeks(1);
        System.out.println("明天: " + tomorrow);
        System.out.println("上周: " + lastWeek);
​
        // 6. 获取时间单位值
        int year = now.getYear();
        Month month = now.getMonth();
        int day = now.getDayOfMonth();
        int hour = now.getHour();
        System.out.printf("时间单位: %d年 %s月 %d日 %d时%n", year, month, day, hour);
​
        // 7. 日期时间比较
        boolean isBefore = now.isBefore(specificDate);
        boolean isAfter = now.isAfter(specificDate);
        System.out.println("当前时间在指定时间之前: " + isBefore);
        System.out.println("当前时间在指定时间之后: " + isAfter);
​
        // 8. 计算时间间隔
        LocalDateTime start = LocalDateTime.of(2023, 1, 1, 0, 0);
        Duration duration = Duration.between(start, now);
        System.out.println("间隔天数: " + duration.toDays());
        System.out.println("间隔小时: " + duration.toHours());
        System.out.println("间隔分钟: " + duration.toMinutes());
​
        // 9. 时区转换
        ZonedDateTime zonedDateTime = now.atZone(ZoneId.of("Asia/Shanghai"));
        ZonedDateTime newYorkTime = zonedDateTime.withZoneSameInstant(ZoneId.of("America/New_York"));
        System.out.println("上海时间: " + zonedDateTime);
        System.out.println("纽约时间: " + newYorkTime);
​
        // 10. 与Date互转
        Instant instant = now.atZone(ZoneId.systemDefault()).toInstant();
        java.util.Date legacyDate = java.util.Date.from(instant);
        System.out.println("传统Date对象: " + legacyDate);
    }
}

关键场景说明:

  1. 获取当前时间
    LocalDateTime.now() 获取系统当前日期时间
  2. 创建指定时间
    LocalDateTime.of() 创建精确到分钟的时间对象
  3. 日期时间转字符串
    **使用 **DateTimeFormatter 自定义格式(如 "yyyy-MM-dd HH🇲🇲ss")
  4. 字符串转日期时间
    LocalDateTime.parse() 配合格式化器解析字符串
  5. 日期时间加减
    plusDays(), minusHours() 等方法进行时间运算
  6. 获取时间单位
    getYear(), getMonth() 等方法提取时间分量
  7. 时间比较
    isBefore(), isAfter() 方法比较时间先后
  8. 计算时间间隔
    Duration.between() 计算两个时间的差值
  9. 时区转换
    **通过 **atZone()withZoneSameInstant() 处理时区
  10. 与传统Date互转
    **通过 **Instant 对象实现与旧版Date的转换

高级用法:

// 1. 调整到特定时间
LocalDateTime nextMonday = now.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
​
// 2. 自定义加减时间量
LocalDateTime in3Hours = now.plus(3, ChronoUnit.HOURS);
LocalDateTime before15Minutes = now.minus(15, ChronoUnit.MINUTES);
​
// 3. 计算工作日间隔
long workingDays = now.datesUntil(nextMonday)
        .filter(date -> !Arrays.asList(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY).contains(date.getDayOfWeek()))
        .count();
​
// 4. 时间段检查
boolean isWithinRange = now.isAfter(start) && now.isBefore(end);
​
// 5. 格式本地化
DateTimeFormatter frenchFormatter = DateTimeFormatter
        .ofLocalizedDateTime(FormatStyle.MEDIUM)
        .withLocale(Locale.FRANCE);

最佳实践(注意事项):

  1. 时区处理:始终明确时区,避免隐式使用系统默认时区
  2. 不可变性:所有操作返回新对象,原对象不变
  3. 线程安全LocalDateTime 是线程安全的类
  4. 格式化重用:复用 DateTimeFormatter 实例提升性能
  5. 空值处理:使用 Optional 包装可能为空的日期时间值

标题:LocalDateTime操作
作者:jackssybin
地址:https://jackssybin.cn/articles/2025/07/16/1752652246705.html

评论

发表评论


取消