Java 8 LocalDate、LocalDateTime 时间日期处理介绍

参考:

Java 8 LocalDate、LocalDateTime 时间处理介绍

时间相关类

时间相关类介绍
LocalDateTime时间处理类,最高精确到纳秒
LocalDate时间处理类,最高精确到天
DateTimeFormatter时间格式化
ZoneId时区设置类

在这里插入图片描述

Java 8仍然延用了ISO的日历体系,并且与它的前辈们不同,
java.time包中的类是不可变且线程安全的。 新的时间及日期API位于java.time包中,下面是里面的一些关键的类:

  • Instant——它代表的是时间戳
  • LocalDate——不包含具体时间的日期,比如2014-01-14。它可以用来存储生日,周年纪念日,入职日期等。
  • LocalTime——它代表的是不含日期的时间
  • LocalDateTime——它包含了日期及时间,不过还是没有偏移信息或者说时区。
  • ZonedDateTime——这是一个包含时区的完整的日期时间,偏移量是以UTC/格林威治时间为基准的。
    新的库还增加了ZoneOffsetZoned,可以为时区提供更好的支持。有了新的DateTimeFormatter之后日期的解析及格式化也变得焕然一新了。

该包的API提供了大量相关的方法,这些方法一般有一致的方法前缀:

  • of: 静态工厂方法。
  • parse: 静态工厂方法,关注于解析。
  • get: 获取某些东西的值。
  • is: 检查某些东西的是否是true。
  • with: 不可变的setter等价物。
  • plus: 加一些量到某个对象。
  • minus: 从某个对象减去一些量。
  • to: 转换到另一个类型。
  • at: 把这个对象与另一个对象组合起来,例如: date.atTime(time)

时区:

    public static void testZonedDateTime(){
        // 获取当前时间日期
        ZonedDateTime date1 = ZonedDateTime.parse("2015-12-03T10:15:30+05:30[Asia/Shanghai]");
        System.out.println("date1: " + date1);
        //date1: 2015-12-03T10:15:30+08:00[Asia/Shanghai]

        ZoneId id = ZoneId.of("Europe/Paris");
        System.out.println("ZoneId: " + id);
        //ZoneId: Europe/Paris

        ZoneId currentZone = ZoneId.systemDefault();
        System.out.println("当期时区: " + currentZone);
        //当期时区: Asia/Shanghai
    }

时间获取

/**
 * 时间获取
 * 使用不同的类可以获取不同精度的时间。
 */
public static void nowTimeTest() {
    // 当前精确时间
    LocalDateTime now = LocalDateTime.now();
    System.out.println("当前精确时间:" + now);
    System.out.println("当前精确时间:"
            + now.getYear() + "-"
            + now.getMonthValue() + "-"
            + now.getDayOfMonth() + " "
            + now.getHour() + "-"
            + now.getMinute() + "-"
            + now.getSecond());
    //当前精确时间:2023-08-22T13:51:03.844
    //当前精确时间:2023-8-22 13-51-3

    // 获取当前日期
    LocalDate localDate = LocalDate.now();
    System.out.println("当前日期:" + localDate);
    System.out.println("当前日期:"
            + localDate.getYear() + "-"
            + localDate.getMonthValue() + "-"
            + localDate.getDayOfMonth());
    //当前日期:2023-08-22
    //当前日期:2023-8-22

    // 获取当天时间
    LocalTime localTime = LocalTime.now();
    System.out.println("当天时间:" + localTime);
    System.out.println("当天时间:"
            + localTime.getHour() + ":"
            + localTime.getMinute() + ":"
            + localTime.getSecond());
    //当天时间:13:51:03.844
    //当天时间:13:51:3

    // 有时区的当前精确时间
    ZonedDateTime nowZone = LocalDateTime.now().atZone(ZoneId.systemDefault());
    System.out.println("当前精确时间(有时区):" + nowZone);
    System.out.println("当前精确时间(有时区):"
            + nowZone.getYear() + "-"
            + nowZone.getMonthValue() + "-"
            + nowZone.getDayOfMonth() + " "
            + nowZone.getHour() + "-"
            + nowZone.getMinute() + "-"
            + nowZone.getSecond());
    //当前精确时间(有时区):2023-08-22T13:51:03.844+08:00[Asia/Shanghai]
    //当前精确时间(有时区):2023-8-22 13-51-3
}

时间创建

/**
 * 时间创建
 * 可以指定年月日时分秒创建一个时间类,也可以使用字符串直接转换成时间。
 */
public static void createTime() {
    LocalDateTime ofTime = LocalDateTime.of(2019, 10, 1, 8, 8, 8);
    System.out.println("当前精确时间:" + ofTime);
    //当前精确时间:2019-10-01T08:08:08

    LocalDate localDate = LocalDate.of(2019, 10, 01);
    System.out.println("当前日期:" + localDate);
    //当前日期:2019-10-01

    LocalTime localTime = LocalTime.of(12, 01, 01);
    System.out.println("当天时间:" + localTime);
    //当天时间:12:01:01
}

日期转换

/**
 * 日期转换
 */
public static void convertTimeTest() {
    LocalDateTime parseTime = LocalDateTime.parse("2019-10-01T22:22:22.222");
    System.out.println("字符串时间转换:" + parseTime);
    //字符串时间转换:2019-10-01T22:22:22.222

    LocalDate formatted = LocalDate.parse("20190101", DateTimeFormatter.BASIC_ISO_DATE);
    System.out.println("字符串时间转换-指定格式:" + formatted);
    //字符串时间转换-指定格式:2019-01-01

    // Date 转换成 LocalDateTime
    Date date = new Date();
    ZoneId zoneId = ZoneId.systemDefault();
    System.out.println("Date 转换成 LocalDateTime:" + LocalDateTime.ofInstant(date.toInstant(), zoneId));
    //Date 转换成 LocalDateTime:2023-08-22T13:56:42.752

    // LocalDateTime 转换成 Date
    LocalDateTime localDateTime = LocalDateTime.now();
    Date toDate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    System.out.println("LocalDateTime 转换成 Date:" + toDate);
    //LocalDateTime 转换成 Date:Tue Aug 22 13:56:42 CST 2023

    // 当前时间转时间戳
    long epochMilli = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
    System.out.println("当前时间转时间戳:" + epochMilli);
    //当前时间转时间戳:1692683802759

    // 时间戳转换成时间
    LocalDateTime epochMilliTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(epochMilli), ZoneId.systemDefault());
    System.out.println("时间戳转换成时间:" + epochMilliTime);
    //时间戳转换成时间:2023-08-22T13:56:42.759
}

日期格式化

/**
 * 日期格式化
 */
public static void formatTest() {
    LocalDateTime now = LocalDateTime.now();
    System.out.println("当前时间:" + now);
    //当前时间:2023-08-22T13:56:42.760
    System.out.println("格式化后:" + now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
    //格式化后:2023-08-22T13:56:42.76
    System.out.println("格式化后:" + now.format(DateTimeFormatter.ISO_LOCAL_DATE));
    //格式化后:2023-08-22
    System.out.println("格式化后:" + now.format(DateTimeFormatter.ISO_LOCAL_TIME));
    //格式化后:13:56:42.76
    System.out.println("格式化后:" + now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
    //格式化后:2023-08-22 01:56:42
}

时间比较


/**
 * 时间比较
 */
public static void diffTest() {
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime yestory = now.minusDays(1);
    System.out.println(now + "在" + yestory + "之后吗?" + now.isAfter(yestory));
    //2023-08-22T13:56:42.766在2023-08-21T13:56:42.766之后吗?true
    System.out.println(now + "在" + yestory + "之前吗?" + now.isBefore(yestory));
    //2023-08-22T13:56:42.766在2023-08-21T13:56:42.766之前吗?false

    // 时间差
    long day = yestory.until(now, ChronoUnit.DAYS);
    long month = yestory.until(now, ChronoUnit.MONTHS);
    long hours = yestory.until(now, ChronoUnit.HOURS);
    long minutes = yestory.until(now, ChronoUnit.MINUTES);
    System.out.println("相差月份" + month);
    //相差月份0
    System.out.println("相差天数" + day);
    //相差天数1
    System.out.println("相差小时" + hours);
    //相差小时24
    System.out.println("相差分钟" + minutes);
    //相差分钟1440

    // 距离JDK 14 发布还有多少天?
    LocalDate jdk14 = LocalDate.of(2020, 3, 17);
    LocalDate nowDate = LocalDate.now();
    System.out.println("距离JDK 14 发布还有:" + nowDate.until(jdk14, ChronoUnit.DAYS) + "天");
    //距离JDK 14 发布还有:-1253天
}

日期加减

/**
 * 日期加减
 */
public static void calcTest() {
    LocalDateTime now = LocalDateTime.now();
    System.out.println("当前时间:" + now);
    //当前时间:2023-08-22T15:14:10.106
    LocalDateTime plusTime = now.plusMonths(1).plusDays(1).plusHours(1).plusMinutes(1).plusSeconds(1);
    System.out.println("增加1月1天1小时1分钟1秒时间后:" + plusTime);
    //增加1月1天1小时1分钟1秒时间后:2023-09-23T16:15:11.106
    LocalDateTime minusTime = now.minusMonths(2);
    System.out.println("减少2个月时间后:" + minusTime);
    //减少2个月时间后:2023-06-22T15:14:10.106
}

本月第一天

public static void firstDayOfMonth() {
    // 当前精确时间
    LocalDateTime now = LocalDateTime.now();
    // LocalDateTime 本月第一天
    // 方法1
    LocalDateTime firstDay = now.withDayOfMonth(1);
    System.out.println("本月第一天:" + firstDay);
    //本月第一天:2023-08-01T15:14:10.106

    // 方法2
    firstDay = now.with(TemporalAdjusters.firstDayOfMonth());
    System.out.println("本月第一天:" + firstDay);
    //本月第一天:2023-08-01T15:14:10.106
}

本月最后一天

public static void lastDayOfMonth() {
    // 当前精确时间
    LocalDateTime now = LocalDateTime.now();
    // LocalDateTime 本月最后一天
    LocalDateTime lastDay = now.with(TemporalAdjusters.lastDayOfMonth());
    System.out.println("本月最后一天:" + lastDay);
    //本月最后一天:2023-08-31T15:14:10.107
}

当天最后一秒

public static void lastSecondOfDay() {
    // 当前精确时间
    LocalDateTime now = LocalDateTime.now();
    // LocalDateTime 当天最后一秒
    // 方法1
    LocalDateTime lastSecondOfDay1 = now.withHour(23).withMinute(59).withSecond(59);
    System.out.println("当天最后一秒:" + lastSecondOfDay1);
    //当天最后一秒:2023-08-22T23:59:59.107
    // 方法2
    LocalDateTime lastSecondOfDay2 = LocalDateTime.now().with(LocalTime.MAX);
    System.out.println("当天最后一秒:" + lastSecondOfDay2);
    //当天最后一秒:2023-08-22T23:59:59.999999999
}

是否闰年

public static void isLeap() {
    // 当前精确时间
    LocalDateTime now = LocalDateTime.now();
    // 是否闰年
    System.out.println("今年是否闰年:" + Year.isLeap(now.getYear()));
    //今年是否闰年:false
}

demo:

package com.xq.demo.java8;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;

public class Test1 {

    public static void main(String[] args) {
        nowTimeTest();

        System.out.println();
        createTime();

        System.out.println();
        convertTimeTest();

        System.out.println();
        formatTest();

        System.out.println();
        diffTest();

        System.out.println();
        calcTest();

        System.out.println();
        firstDayOfMonth();

        System.out.println();
        lastDayOfMonth();

        System.out.println();
        lastSecondOfDay();

        System.out.println();
        isLeap();
    }

    /**
     * 时间获取
     * 使用不同的类可以获取不同精度的时间。
     */
    public static void nowTimeTest() {
        // 当前精确时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前精确时间:" + now);
        System.out.println("当前精确时间:"
                + now.getYear() + "-"
                + now.getMonthValue() + "-"
                + now.getDayOfMonth() + " "
                + now.getHour() + "-"
                + now.getMinute() + "-"
                + now.getSecond());
        //当前精确时间:2023-08-22T13:51:03.844
        //当前精确时间:2023-8-22 13-51-3

        // 获取当前日期
        LocalDate localDate = LocalDate.now();
        System.out.println("当前日期:" + localDate);
        System.out.println("当前日期:"
                + localDate.getYear() + "-"
                + localDate.getMonthValue() + "-"
                + localDate.getDayOfMonth());
        //当前日期:2023-08-22
        //当前日期:2023-8-22

        // 获取当天时间
        LocalTime localTime = LocalTime.now();
        System.out.println("当天时间:" + localTime);
        System.out.println("当天时间:"
                + localTime.getHour() + ":"
                + localTime.getMinute() + ":"
                + localTime.getSecond());
        //当天时间:13:51:03.844
        //当天时间:13:51:3

        // 有时区的当前精确时间
        ZonedDateTime nowZone = LocalDateTime.now().atZone(ZoneId.systemDefault());
        System.out.println("当前精确时间(有时区):" + nowZone);
        System.out.println("当前精确时间(有时区):"
                + nowZone.getYear() + "-"
                + nowZone.getMonthValue() + "-"
                + nowZone.getDayOfMonth() + " "
                + nowZone.getHour() + "-"
                + nowZone.getMinute() + "-"
                + nowZone.getSecond());
        //当前精确时间(有时区):2023-08-22T13:51:03.844+08:00[Asia/Shanghai]
        //当前精确时间(有时区):2023-8-22 13-51-3
    }

    /**
     * 时间创建
     * 可以指定年月日时分秒创建一个时间类,也可以使用字符串直接转换成时间。
     */
    public static void createTime() {
        LocalDateTime ofTime = LocalDateTime.of(2019, 10, 1, 8, 8, 8);
        System.out.println("当前精确时间:" + ofTime);
        //当前精确时间:2019-10-01T08:08:08

        LocalDate localDate = LocalDate.of(2019, 10, 01);
        System.out.println("当前日期:" + localDate);
        //当前日期:2019-10-01

        LocalTime localTime = LocalTime.of(12, 01, 01);
        System.out.println("当天时间:" + localTime);
        //当天时间:12:01:01
    }

    /**
     * 日期转换
     */
    public static void convertTimeTest() {
        LocalDateTime parseTime = LocalDateTime.parse("2019-10-01T22:22:22.222");
        System.out.println("字符串时间转换:" + parseTime);
        //字符串时间转换:2019-10-01T22:22:22.222

        LocalDate formatted = LocalDate.parse("20190101", DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println("字符串时间转换-指定格式:" + formatted);
        //字符串时间转换-指定格式:2019-01-01

        // Date 转换成 LocalDateTime
        Date date = new Date();
        ZoneId zoneId = ZoneId.systemDefault();
        System.out.println("Date 转换成 LocalDateTime:" + LocalDateTime.ofInstant(date.toInstant(), zoneId));
        //Date 转换成 LocalDateTime:2023-08-22T13:56:42.752

        // LocalDateTime 转换成 Date
        LocalDateTime localDateTime = LocalDateTime.now();
        Date toDate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        System.out.println("LocalDateTime 转换成 Date:" + toDate);
        //LocalDateTime 转换成 Date:Tue Aug 22 13:56:42 CST 2023

        // 当前时间转时间戳
        long epochMilli = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        System.out.println("当前时间转时间戳:" + epochMilli);
        //当前时间转时间戳:1692683802759

        // 时间戳转换成时间
        LocalDateTime epochMilliTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(epochMilli), ZoneId.systemDefault());
        System.out.println("时间戳转换成时间:" + epochMilliTime);
        //时间戳转换成时间:2023-08-22T13:56:42.759
    }

    /**
     * 日期格式化
     */
    public static void formatTest() {
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前时间:" + now);
        //当前时间:2023-08-22T13:56:42.760
        System.out.println("格式化后:" + now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        //格式化后:2023-08-22T13:56:42.76
        System.out.println("格式化后:" + now.format(DateTimeFormatter.ISO_LOCAL_DATE));
        //格式化后:2023-08-22
        System.out.println("格式化后:" + now.format(DateTimeFormatter.ISO_LOCAL_TIME));
        //格式化后:13:56:42.76
        System.out.println("格式化后:" + now.format(DateTimeFormatter.ofPattern("YYYY-MM-dd hh:mm:ss")));
        //格式化后:2023-08-22 01:56:42
    }

    /**
     * 时间比较
     */
    public static void diffTest() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime yestory = now.minusDays(1);
        System.out.println(now + "在" + yestory + "之后吗?" + now.isAfter(yestory));
        //2023-08-22T13:56:42.766在2023-08-21T13:56:42.766之后吗?true
        System.out.println(now + "在" + yestory + "之前吗?" + now.isBefore(yestory));
        //2023-08-22T13:56:42.766在2023-08-21T13:56:42.766之前吗?false

        // 时间差
        long day = yestory.until(now, ChronoUnit.DAYS);
        long month = yestory.until(now, ChronoUnit.MONTHS);
        long hours = yestory.until(now, ChronoUnit.HOURS);
        long minutes = yestory.until(now, ChronoUnit.MINUTES);
        System.out.println("相差月份" + month);
        //相差月份0
        System.out.println("相差天数" + day);
        //相差天数1
        System.out.println("相差小时" + hours);
        //相差小时24
        System.out.println("相差分钟" + minutes);
        //相差分钟1440

        // 距离JDK 14 发布还有多少天?
        LocalDate jdk14 = LocalDate.of(2020, 3, 17);
        LocalDate nowDate = LocalDate.now();
        System.out.println("距离JDK 14 发布还有:" + nowDate.until(jdk14, ChronoUnit.DAYS) + "天");
        //距离JDK 14 发布还有:-1253天
    }

    /**
     * 日期加减
     */
    public static void calcTest() {
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前时间:" + now);
        //当前时间:2023-08-22T15:14:10.106
        LocalDateTime plusTime = now.plusMonths(1).plusDays(1).plusHours(1).plusMinutes(1).plusSeconds(1);
        System.out.println("增加1月1天1小时1分钟1秒时间后:" + plusTime);
        //增加1月1天1小时1分钟1秒时间后:2023-09-23T16:15:11.106
        LocalDateTime minusTime = now.minusMonths(2);
        System.out.println("减少2个月时间后:" + minusTime);
        //减少2个月时间后:2023-06-22T15:14:10.106
    }

    public static void firstDayOfMonth() {
        // 当前精确时间
        LocalDateTime now = LocalDateTime.now();
        // LocalDateTime 本月第一天
        // 方法1
        LocalDateTime firstDay = now.withDayOfMonth(1);
        System.out.println("本月第一天:" + firstDay);
        //本月第一天:2023-08-01T15:14:10.106

        // 方法2
        firstDay = now.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println("本月第一天:" + firstDay);
        //本月第一天:2023-08-01T15:14:10.106
    }

    public static void lastDayOfMonth() {
        // 当前精确时间
        LocalDateTime now = LocalDateTime.now();
        // LocalDateTime 本月最后一天
        LocalDateTime lastDay = now.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("本月最后一天:" + lastDay);
        //本月最后一天:2023-08-31T15:14:10.107
    }

    public static void lastSecondOfDay() {
        // 当前精确时间
        LocalDateTime now = LocalDateTime.now();
        // LocalDateTime 当天最后一秒
        // 方法1
        LocalDateTime lastSecondOfDay1 = now.withHour(23).withMinute(59).withSecond(59);
        System.out.println("当天最后一秒:" + lastSecondOfDay1);
        //当天最后一秒:2023-08-22T23:59:59.107
        // 方法2
        LocalDateTime lastSecondOfDay2 = LocalDateTime.now().with(LocalTime.MAX);
        System.out.println("当天最后一秒:" + lastSecondOfDay2);
        //当天最后一秒:2023-08-22T23:59:59.999999999
    }

    public static void isLeap() {
        // 当前精确时间
        LocalDateTime now = LocalDateTime.now();
        // 是否闰年
        System.out.println("今年是否闰年:" + Year.isLeap(now.getYear()));
        //今年是否闰年:false
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值