Java语言12之时间类

1 时间

1.1 LocalDate

API根据用途的不同,大概可以分为如下几类

  • 创建LocalDate对象:now()、of()等等
  • 获取LocalDate对象属性:getYear()、getMonth()、getDayOfYear()、getDayOfMonth()、getDayOfWeek()等等
  • 设置LocalDate对象属性:withYear()、withMonth()、withDayOfYear()、withDayOfMonth()、plusDays()、plusMonths()、minusDays()等等
  • 比较LocalDate对象:isEqual()、isBefore()、isAfter()
public class TestLocalDate {
    @Test
    public void testCreate(){
        LocalDate getDateByNow = LocalDate.now();
        System.out.println(getDateByNow);

        LocalDate getDateByOf = LocalDate.of(2024, 5, 21);
        System.out.println(getDateByOf);
    }

    @Test
    public void testGet(){
        LocalDate date = LocalDate.now();
        System.out.println("Year = " + date.getYear());
        System.out.println("Month = " + date.getMonth());
        System.out.println("Month->Value = " + date.getMonth().getValue());
        System.out.println("DayOfYear = " + date.getDayOfYear());
        System.out.println("DayOfMonth = " + date.getDayOfMonth());
        System.out.println("DayOfWeek = " + date.getDayOfWeek());
        System.out.println("DayOfWeek->Value = " + date.getDayOfWeek().getValue());
    }

    // JDK8新增的日期时间对象都是不可变对象,每次修改都会返回一个新对象,即原对象不会被修改
    @Test
    public void testSet() {
        LocalDate oldDate = LocalDate.now();
        LocalDate newDate = oldDate.withYear(2025);
        System.out.println("oldDate = " + oldDate);
        System.out.println("newDate = " + newDate);
    }


    @Test
    public void testPlus(){
        LocalDate oldDate = LocalDate.now();
        LocalDate newDate = oldDate.plusDays(1);
        System.out.println("oldDate = " + oldDate);
        System.out.println("newDate = " + newDate);
    }

    @Test
    public void testMinus(){
        LocalDate oldDate = LocalDate.now();
        LocalDate newDate = oldDate.minusDays(1);
        System.out.println("oldDate = " + oldDate);
        System.out.println("newDate = " + newDate);
    }

    @Test
    public void testCompare(){
        LocalDate oldDate = LocalDate.now();
        LocalDate newDate = oldDate.plusDays(1);

        System.out.println(oldDate.isEqual(newDate));
        System.out.println(oldDate.isBefore(newDate));
        System.out.println(oldDate.isAfter(newDate));
    }
}

1.2 LocalTime

LocalTime和LocalDate用法差不多,直接贴代码

public class TestLocalTime {
    @Test
    public void testCreate(){
        LocalTime getTimeByNow = LocalTime.now();
        System.out.println("getTimeByNow = " + getTimeByNow);
        LocalTime getTimeByOf = LocalTime.of(11, 11, 30, 118);
        System.out.println("getTimeByOf = " + getTimeByOf);
    }

    @Test
    public void testGet(){
        LocalTime now = LocalTime.now();
        System.out.println("now.getHour() = " + now.getHour());
        System.out.println("now.getMinute() = " + now.getMinute());
        System.out.println("now.getSecond() = " + now.getSecond());
        System.out.println("now.getNano() = " + now.getNano());
    }

    @Test
    public void testSet() {
        LocalTime oldTime = LocalTime.now();
        LocalTime newTime = oldTime.withHour(12);
        System.out.println("oldTime = " + oldTime);
        System.out.println("newTime = " + newTime);
    }


    @Test
    public void testPlus(){
        LocalTime oldTime = LocalTime.now();
        LocalTime newTime = oldTime.plusHours(1);
        System.out.println("oldTime = " + oldTime);
        System.out.println("newTime = " + newTime);
    }
}

1.3 LocalDateTime

LocalDateTime兼容了LocalDate和LocalTime,几乎拥有二者的所有API,用法也相同

public class TestLocalDateTime {
    @Test
    public void testCreateAndGet(){
        LocalDateTime now = LocalDateTime.now();
        System.out.println("now.getYear() = " + now.getYear());
        System.out.println("now.getMonth().getValue() = " + now.getMonth().getValue());
        System.out.println("now.getDayOfMonth() = " + now.getDayOfMonth());

        System.out.println("now.getHour() = " + now.getHour());
        System.out.println("now.getMinute() = " + now.getMinute());
        System.out.println("now.getSecond() = " + now.getSecond());
        System.out.println("now.getNano() = " + now.getNano());
    }
}

1.3 Instant

Instant表示时间线上的某个时刻/时间戳。可以用来记录代码的执行时间,或用于记录用户操作某个事件的时间点。传统的Date类,只能精确到毫秒,并且是可变对象;新增的Instant类,可以精确到纳秒,并且是不可变对象,推荐用Instant代替Date。

public class TestInstant {
    public static void main(String[] args) throws InterruptedException {
        // 1、创建Instant的对象,获取此刻时间信息
        Instant now = Instant.now();
        System.out.println(now);

        // 2、获取总秒数
        long epochSecond = now.getEpochSecond();
        System.out.println("epochSecond = " + epochSecond);
        // 毫秒
        long milli = now.toEpochMilli();
        System.out.println("milli = " + milli);
        // 纳秒数
        int nano = now.getNano();
        System.out.println("nano = " + nano);

        // 3、增加、减少系列的方法
        Instant plusSeconds = now.plusSeconds(10);
        System.out.println("plusSeconds = " + plusSeconds);

        Instant minusSeconds = now.minusSeconds(10);
        System.out.println("minusSeconds = " + minusSeconds);

        // 4、判断系列的方法
        System.out.println(plusSeconds.equals(minusSeconds));
        System.out.println(plusSeconds.isAfter(minusSeconds));
        System.out.println(plusSeconds.isBefore(minusSeconds));

        // Instant对象的作用:做代码的性能分析,或者记录用户的操作时间点
        Instant begin = Instant.now();
        TimeUnit.SECONDS.sleep(2);
        Instant end = Instant.now();
        System.out.println("方法执行时间:" + (end.getNano() - begin.getNano()));
    }
}

2 时间间隔

2.1 Period

可以用于计算两个LocalDate对象相差的年数、月数、天数

public class TestPeriod {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2029, 8, 10);
        LocalDate end = LocalDate.of(2029, 12, 15);

        // 1、创建Period对象,封装两个日期对象。
        Period between = Period.between(start, end);
        // 2、通过period对象获取两个日期对象相差的信息。
        System.out.println(between.getDays());
        System.out.println(between.getMonths());
        System.out.println(between.getYears());
    }
}

2.2 Duration

public class TestDuration {
    public static void main(String[] args) {
        LocalDateTime start = LocalDateTime.of(2025, 11, 11, 11, 10, 10);
        LocalDateTime end = LocalDateTime.of(2025, 11, 11, 12, 11, 11);

        // 1、得到Duration对象
        Duration between = Duration.between(start, end);

        // 2、获取两个时间对象间隔的信息
        System.out.println(between.toDays());
        System.out.println(between.toHours());
        System.out.println(between.toMinutes());
        System.out.println(between.toMillis());
        System.out.println(between.toNanos());
    }
}

3 时区

3.1 ZoneId

public class TestZone {
    public static void main(String[] args) {
        // 获取系统默认的时区
        ZoneId z = ZoneId.systemDefault();
        // Asia/Shanghai
        System.out.println(z.getId());
        System.out.println("==========================================");

        // 获取Java支持的全部时区Id
        Set<String> ids = ZoneId.getAvailableZoneIds();
        for (String zoneId : ids) {
            System.out.print(zoneId + ", ");
        }
        System.out.println();
        System.out.println("==========================================");

        // 把某个时区id封装成ZoneId对象。
        ZoneId zoneId = ZoneId.of("America/New_York");
        System.out.println(zoneId);
    }
}

3.2 ZoneTime

public class TestZoneTime {
    public static void main(String[] args) {
        // 获取某个时区的ZonedDateTime对象
        ZoneId newYorkZoneId = ZoneId.of("America/New_York");
        // 纽约时间 -5, 即比世界标准时间-5小时
        ZonedDateTime newYorkTime = ZonedDateTime.now(newYorkZoneId);
        // 2023-11-23T01:47:30.208-05:00[America/New_York]
        System.out.println(newYorkTime);

        // 获取世界标准时间
        ZonedDateTime worldTime = ZonedDateTime.now(Clock.systemUTC());
        // 2023-11-23T06:47:30.242Z
        System.out.println(worldTime);

        // 获取系统默认时区的ZonedDateTime对象
        // 上海时间 +8, 即比世界标准时间+8小时
        ZonedDateTime shanghaiTime = ZonedDateTime.now();
        // 2023-11-23T14:47:30.245+08:00[Asia/Shanghai]
        System.out.println(shanghaiTime);

        // 获取日期时间中的相关信息
        System.out.println(shanghaiTime.getHour());
        System.out.println(shanghaiTime.getDayOfWeek());
    }
}

4 时间格式化

public class TestFormat {
    @Test
    public void testFormat() {
        LocalDateTime dateTime = LocalDateTime.now();
        // 1、创建一个日期时间格式化器对象出来。
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");

        // 2、对时间进行格式化
        // 方式一
        String rs1 = formatter.format(dateTime);
        System.out.println(rs1);

        // 方式二,本质上是一样的
        String rs2 = dateTime.format(formatter);
        System.out.println(rs2);
    }

    @Test
    public void testParse() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse("2023年11月23日 14:35:46", formatter);
        System.out.println(localDateTime);
    }
}

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值