Java8新特性_新时间与日期API-本地时间与时间戳

package com.zs.boot.controller;

import org.junit.Test;

import java.time.*;

public class TestlocalDateTime {
    //1. LocalDate、LocalTime、LocalDateTime
    @Test
    public void test(){
        LocalDateTime ldt = LocalDateTime.now();
        System.out.println(ldt);//2021-12-05T09:51:05.370

        LocalDateTime ldt2 = LocalDateTime.of(2021,12,06,13,15,25);
        System.out.println(ldt2);//2021-12-06T13:15:25

        LocalDateTime ldt3 = ldt.plusYears(2);
        System.out.println(ldt3);//2023-12-05T09:55:55.441

        LocalDateTime ldt4 = ldt.minusMonths(2);
        System.out.println(ldt4);//2021-10-05T09:58:43.908

        System.out.println(ldt.getYear());
        System.out.println(ldt.getMonthValue());
        System.out.println(ldt.getDayOfMonth());
        System.out.println(ldt.getHour());
        System.out.println(ldt.getMinute());
        System.out.println(ldt.getSecond());
    }

    //2. Instant : 时间戳。 (使用 Unix 元年  1970年1月1日 00:00:00 所经历的毫秒值)
    @Test
    public void test2(){
        Instant ins = Instant.now();  //默认使用 UTC 时区
        System.out.println(ins);//2021-12-05T02:45:08.546Z

        OffsetDateTime odt = ins.atOffset(ZoneOffset.ofHours(8));
        System.out.println(odt);//2021-12-05T10:45:08.546+08:00

        //纳秒
        System.out.println(ins.getNano());//546000000

        Instant ins2 = Instant.ofEpochSecond(5);//加5秒
        System.out.println(ins2);//1970-01-01T00:00:05Z
    }

    //3.计算
    //Duration : 用于计算两个“时间”间隔
    //Period : 用于计算两个“日期”间隔
    @Test
    public void test3(){
        Instant ins1 = Instant.now();

        System.out.println("--------------------");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }

        Instant ins2 = Instant.now();

        System.out.println("所耗费时间为:" + Duration.between(ins1, ins2));//所耗费时间为:PT1S

        System.out.println("----------------------------------");

        LocalDate ld1 = LocalDate.now();
        LocalDate ld2 = LocalDate.of(2020, 1, 1);

        Period pe = Period.between(ld2, ld1);
        System.out.println(pe.getYears()); //1
        System.out.println(pe.getMonths());//11
        System.out.println(pe.getDays());  //4
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZHOU_VIP

您的鼓励将是我创作最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值