Java8-新的日期和时间API

本文介绍了Java 8中对日期和时间API的升级,包括SimpleDateFormat的替代、线程安全的DateFormatThreadLocal使用,以及LocalDateTime的示例。内容涵盖了线程不安全和安全的日期解析,以及对时区处理、DateTimeFormatter的格式化、TemporalAdjuster的调整功能的演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、Java8之前的日期和时间API

1.1、TestSimpleDateFormat

package com.chenheng;

import com.chenheng.java8.DateFormatThreadLocal;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author chenheng
 * @date 2021/11/28 17:39
 */
@SpringBootTest
public class TestSimpleDateFormat {
    /**
     * 线程不安全的
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Test
    void test01() throws ExecutionException, InterruptedException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Callable<Date> task = () -> sdf.parse("20211128");
        ExecutorService pool = Executors.newFixedThreadPool(10);
        List<Future<Date>> results = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            results.add(pool.submit(task));
        }
        for (Future<Date> future : results) {
            System.out.println(future.get());
        }
        pool.shutdown();
    }

    /**
     * 线程安全的
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Test
    void test02() throws ExecutionException, InterruptedException {
        Callable<Date> task = () -> DateFormatThreadLocal.convert("20211128");
        ExecutorService pool = Executors.newFixedThreadPool(10);
        List<Future<Date>> results = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            results.add(pool.submit(task));
        }
        for (Future<Date> future : results) {
            System.out.println(future.get());
        }
        pool.shutdown();
    }

    /**
     * java8新特性
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Test
    void test03() throws ExecutionException, InterruptedException {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
        Callable<LocalDate> task = () -> LocalDate.parse("20211128", dtf);
        ExecutorService pool = Executors.newFixedThreadPool(10);
        List<Future<LocalDate>> results = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            results.add(pool.submit(task));
        }
        for (Future<LocalDate> future : results) {
            System.out.println(future.get());
        }
        pool.shutdown();
    }
}

1.2、DateFormatThreadLocal

package com.chenheng.java8;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author chenheng
 * @date 2021/11/28 17:53
 */
public class DateFormatThreadLocal {
    private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>(){
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyyMMdd");
        }
    };
    public static Date convert(String source) throws ParseException {
        return df.get().parse(source);
    }
}

2、Java8的日期和时间API

2.1、TestLocalDateTime

package com.chenheng;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

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

/**
 * @author chenheng
 * @date 2021/11/28 20:51
 */
@SpringBootTest
public class TestLocalDateTime {
    //ZonedDate、ZonedTime、ZonedDateTime
    @Test
    void test08(){
        //当前系统时间对应的(指定)时区时间(不带时区)
        LocalDateTime now = LocalDateTime.now(ZoneId.of("Europe/Tallinn"));
        System.out.println(now);
        //当前系统时间对应带时区的时间
        LocalDateTime ldt2 = LocalDateTime.now(ZoneId.of("Europe/Tallinn"));
        System.out.println("ldt2->"+ldt2);
        ZonedDateTime zonedDateTime = ldt2.atZone(ZoneId.of("Europe/Tallinn"));
        System.out.println("zonedDateTime->"+zonedDateTime);
        System.out.println("*****************************");
        LocalDateTime shanghaiLdt = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
        ZonedDateTime shanghaiZonedDateTime = shanghaiLdt.atZone(ZoneId.of("Asia/Shanghai"));
        System.out.println("shanghaiZonedDateTime->"+shanghaiZonedDateTime);
    }
    /**
     * 获取世界上所有的时区
     */
    @Test
    void test07(){
        Set<String> set = ZoneId.getAvailableZoneIds();
        set.forEach(System.out::println);
    }
    /**
     * DateTimeFormatter:格式化时间/日期
     */
    @Test
    void test06(){
        DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE;
        LocalDateTime ldt = LocalDateTime.now();
        String strDate = dtf.format(ldt);
        System.out.println("strDate->"+strDate);
        System.out.println("*****************");
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
        String strDate2 = dtf2.format(ldt);
        System.out.println("strDate2->"+strDate2);
        LocalDateTime lastDate = LocalDateTime.parse(strDate2, dtf2);
        System.out.println("lastDate->"+lastDate);
    }
    /**
     * TemporalAdjuster:时间矫正器
     */
    @Test
    void test05(){
        LocalDateTime ldt = LocalDateTime.now();
        System.out.println("ldt->"+ldt);
        LocalDateTime ldt2 = ldt.withDayOfMonth(10);
        System.out.println("ldt2->"+ldt2);
        //当前日期的下一个周日
        LocalDateTime ldt3 = ldt.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
        System.out.println("ldt3->"+ldt3);
        //自定义:下一个工作日
        LocalDateTime ldt5 = ldt.with((l) -> {
            LocalDateTime ldt4 = (LocalDateTime) l;
            DayOfWeek dayOfWeek = ldt4.getDayOfWeek();
            if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {
                return ldt4.plusDays(3);
            } else if (dayOfWeek.equals(DayOfWeek.SATURDAY)) {
                return ldt4.plusDays(2);
            } else {
                return ldt4.plusDays(1);
            }
        });
        System.out.println("ldt5->"+ldt5);
    }
    /**
     * Duration:计算两个“时间”之间的间隔
     * Period:计算两个“日期”之间的间隔
     */
    @Test
    void test04(){
        LocalDate localDate1 = LocalDate.of(2021, 7, 26);
        LocalDate now = LocalDate.now();
        Period p = Period.between(localDate1, now);
        System.out.println(p);
        System.out.println("years->"+p.getYears());
        System.out.println("months->"+p.getMonths());
        System.out.println("days->"+p.getDays());
        System.out.println("allDays->"+p.get(ChronoUnit.DAYS));
    }
    @Test
    void test03(){
        Instant ins1 = Instant.now();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        Instant ins2 = Instant.now();
        Duration duration = Duration.between(ins1, ins2);
        System.out.println("toMillis->"+duration.toMillis());
        System.out.println("******************************");
        LocalTime localTime1 = LocalTime.now();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        LocalTime localTime2 = LocalTime.now();
        System.out.println(Duration.between(localTime1, localTime2).toMillis());
    }
    /**
     * 2.Instant:时间戳(以 Unix 元年:1970年1月1日00:00:00 到某个时间之间的毫秒值)
     */
    @Test
    void test02(){
        //默认获取 UTC 时区,英国格林尼治时间
        Instant now = Instant.now();
        System.out.println("now->"+now);
        //东八区时间
        OffsetDateTime offsetDateTime = now.atOffset(ZoneOffset.ofHours(8));
        System.out.println("offsetDateTime->"+offsetDateTime);
        System.out.println(now.toEpochMilli());
        Instant instant2 = Instant.ofEpochSecond(60);
        System.out.println(instant2);
    }
    /**
     * 日期-LocalDate 时间-LocalTime 日期时间-LocalDateTime
     */
    @Test
    void test01(){
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);

        LocalDateTime ldt = LocalDateTime.of(2021, 11, 28, 20, 53);
        LocalDateTime plusMonths = ldt.plusMonths(1);
        System.out.println("plusMonths->"+plusMonths);
        LocalDateTime minusMonths = ldt.minusMonths(1);
        System.out.println("minusMonths->"+minusMonths);
        LocalDateTime plusDays = ldt.plusDays(1);
        System.out.println("plusDays->"+plusDays);
        System.out.println("year->"+ldt.getYear());
        System.out.println("month->"+ldt.getMonthValue());
        System.out.println("day->"+ldt.getDayOfMonth());
        System.out.println("hour->"+ldt.getHour());
        System.out.println("minute->"+ldt.getMinute());
    }

    /**
     * 获得一天开始时间和结束时间
     */
    @Test
    void test0101(){
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime sDateTime = LocalDateTime.of(now.toLocalDate(), LocalTime.MIN);
        String startDay = sDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println("startDay->"+startDay);
        LocalDateTime eDateTime = LocalDateTime.of(now.toLocalDate(), LocalTime.MAX);
        String endDay = eDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println("endDay->"+endDay);
    }
}

3、参考链接

1、Java8日期视频

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值