死磕 Java 8 的日期处理

TIME
  • Java 8 推出了全新的日期时间API并且已经很久了,因为业务中遇到的时间处理的还是不多,因此用的也少,而且大多是用封装好的时间共计包,就更少接触java8 的时间类型API了,因此对他不是很熟,今天遇到了一下问题打算总结一下:
  • Java处理日期、日历和时间的不足之处:将 java.util.Date 设定为可变类型,以及 SimpleDateFormat 的非线程安全使其应用非常受限。然后就在 java8 上面增加新的特性。
  • 全新API的好处之一就是,明确了日期时间概念,例如:瞬时(instant)、 长短(duration)、日期、时间、时区和周期这些概念都是分开的,并且有独立的对象来处理。
  • 重要的是:同时继承了Joda 库按人类语言和计算机各自解析的时间处理方式。不同于老版本,新API基于ISO标准日历系统,java.time包下的***所有类都是不可变类型而且线程安全***。
关键类
  • Instant:瞬时实例。
  • LocalTime:本地时间,不包含日期。只有时分秒纳秒等信息
  • LocalDate:本地日期,不包含具体时间 例如:2014-01-14 可以用来记录生日、纪念日、加盟日等。只有年月日信息
  • LocalDateTime:组合了日期和时间,但不包含时差和时区信息。包含所有年月日时分秒纳秒等信息
  • 以上三个是类似的PAI,都有差不多一样的方法和处理方式,只是表达的时间范围是不一样的。这一点用起来还是非常方便的
  • ZonedDateTime:最完整的日期时间,包含时区和相对UTC或格林威治的时差。这个类用来处理带时区的时间信息
  • 新API还引入了 ZoneOffSet 和 ZoneId 类,使得解决时区问题更为简便。解析、格式化时间的 DateTimeFormatter 类也全部重新设计。具体时区用这两个处理
当前时间
/**
     * java时间类型,新旧api对比
     */
    public static void getCurrentDate() {
        LocalDate today = LocalDate.now();
        System.out.println("today's local date: " + today);
        Date date = new Date();
        System.out.println("today's date is: " + date);
    }
获取对应时间年月日,时分秒
/**
     * LocalDate 获取年月日信息,与之前Calendar对比
     */
    public static void getDetailDate() {
        LocalTime todayTime = LocalTime.now();
        int second = todayTime.getSecond();
        int minute = todayTime.getMinute();
        int hour = todayTime.getHour();
        int nano = todayTime.getNano();
        System.out.println("秒: " + second + "分: " + minute + "时: " + hour + "纳秒: " + nano);
        
        LocalDate today = LocalDate.now();
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();
        int day_year = today.getDayOfYear();
        System.out.println(year + ": " + month + ": " + day + ": " + day_year);
        
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime.getHour());
    }
处理特定日志 & 时间对比
 /**
     * 处理特定日志 & 时间对比
     */
    public static void handleSpecilDate() {
        LocalDate localDate = LocalDate.of(2021, 11, 18);
        System.out.println(localDate);
        LocalDate date = LocalDate.of(2021, 6, 18);
        System.out.println(localDate.equals(date));
    }
处理生日这种周期性时间
/**
     * 检查生日这种周期性时间
     */
    public static void cycleDate() {
        LocalDate localDate = LocalDate.now();
        LocalDate dateofBirth = LocalDate.of(2021, 6, 18);
        MonthDay birthday = MonthDay.of(dateofBirth.getMonth(), dateofBirth.getDayOfMonth());
        MonthDay nowDate = MonthDay.from(localDate);
        MonthDay monthParse = MonthDay.parse("2021-06-18", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        System.out.println(birthday.equals(nowDate));
        System.out.println(monthParse);
    }
yearMonth处理固定日期
 public static void checkCardExpiry() {
        YearMonth currenctYearMonth = YearMonth.now();
        System.out.println(currenctYearMonth + ": " + currenctYearMonth.lengthOfMonth());
        YearMonth credtCard = YearMonth.of(2021, Month.FEBRUARY);
        System.out.println(credtCard + ": " + credtCard.lengthOfMonth());
        DayOfWeek dayOfWeek = DayOfWeek.of(3);
        System.out.println(dayOfWeek);
    }
时间做加法
 /**
     * 时间做加法
     * LocalTime支持:
     * NANOS
     * MICROS
     * MILLIS
     * SECONDS
     * MINUTES
     * HOURS
     * HALF_DAYS
     */
    public static void plusHours() {
        LocalTime localTime = LocalTime.now();
        localTime.plusHours(5);
        System.out.println(localTime);
        LocalTime nextWeek = localTime.plus(10, ChronoUnit.HOURS);
        System.out.println(nextWeek);
        System.out.println(localTime);
        LocalTime halfDay = localTime.plus(2, ChronoUnit.HALF_DAYS);
        System.out.println(halfDay);
    }

    /**
     * 日期做加法
     */
    public static void plusDate() {
        LocalDate localDate = LocalDate.now();
        LocalDate tomorrow = localDate.plus(1, ChronoUnit.DAYS);
        System.out.println(tomorrow);
        LocalDate nextYear = localDate.plus(1, ChronoUnit.YEARS);
        LocalDate beforeYear = localDate.minus(1, ChronoUnit.YEARS);
        System.out.println("nextYear: " + nextYear);
        System.out.println("beforeYear: " + beforeYear);
    }

    /**
     * 日期+ 时间,
     */
    public static void plusTime() {
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);
        LocalDateTime afterHour = localDateTime.plus(1, ChronoUnit.HOURS).plus(1, ChronoUnit.MINUTES).plus(1, ChronoUnit.YEARS);
        System.out.println(afterHour);
        LocalDateTime nowDate = LocalDateTime.of(2021, 6, 19, 17, 23, 57);
        System.out.println(nowDate);

    }

时间比较
  /**
     * 时间比较api
     */
    public static void checkTimes() {
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime afterDate = LocalDateTime.of(2021, 6, 19, 17, 23, 57);
        System.out.println(localDateTime.isBefore(afterDate));
        System.out.println(localDateTime.isAfter(afterDate));
    }
时区处理
   /**
     * 时区处理
     */
    public static void zoneTime() {
        ZoneId america = ZoneId.of("America/Chicago");
        LocalDateTime dateAndTime = LocalDateTime.now();
        ZonedDateTime dateTimeInChicago = ZonedDateTime.of(dateAndTime, america);
        System.out.println(dateTimeInChicago);
        ZonedDateTime dateTimeInShenZhen = ZonedDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());
        System.out.println(dateTimeInShenZhen);
    }
    
/**
     * 包括时差信息的日期与时间
     */
    public static void zoneOffSet() {
        LocalDateTime localDateTime = LocalDateTime.of(2021, Month.FEBRUARY, 14, 19, 24);
        ZoneOffset offset = ZoneOffset.of("+07:30");
        OffsetDateTime dateTime = OffsetDateTime.of(localDateTime, offset);
        System.out.println(dateTime);
    }
检查闰年
/**
     * 检查闰年
     */
public static void isLeapYear() {
        LocalDate today = LocalDate.now();
        System.out.println(today.getYear() + "年是闰年:" + today.isLeapYear());
    }
计算日期间隔
**
     * 计算日期之间年,月,天数
     */
    public static void calcDate() {
        LocalDate localDateTime = LocalDate.of(2021, 10, 28);
        LocalDate beforeDateTime = LocalDate.now().plus(3, ChronoUnit.DAYS);
        Period period = Period.between(localDateTime, beforeDateTime);
        System.out.println("year: " + period.getYears() + " month:" + period.getMonths() + " day:" + period.getDays());
    }
日期格式
/**
     * 格式化日期
     */
    public static void formatDate() {
        String dayAfterTomorrow = "2021-06-18 15:53:06";
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime formatDateTime = LocalDateTime.parse(dayAfterTomorrow, df);
        System.out.println("timeStr: " + dayAfterTomorrow + " dateTime:" + formatDateTime);

        String dayDate = "20210618";
        DateTimeFormatter dateDayFor = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate localDate = LocalDate.parse(dayDate, dateDayFor);
        System.out.println("timeStr: " + dayDate + " dateTime:" + localDate);

        String dayTime = "160451";
        DateTimeFormatter dayTimeFor = DateTimeFormatter.ofPattern("HHmmss");
        LocalTime localTime = LocalTime.parse(dayTime, dayTimeFor);
        System.out.println("timeStr: " + dayTime + " dateTime:" + localTime);
    }
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值