Java基础-----Date类(二)

发布时间:2024年01月03日

请添加图片描述

今天主要学习JDK8新增日期工具类

1. LocalDate:获取本地日期

获取系统日期和时间

public class Test1 {
    public static void main(String[] args) {
        LocalDate date=LocalDate.now();
        System.out.println(date);
        LocalTime time=LocalTime.now();
        System.out.println(time);
        LocalDateTime dateTime=LocalDateTime.now();
        System.out.println(dateTime);
    }
}

运行结果:
在这里插入图片描述
可以看到,最后日期和时间中间有个T,这就需要去瞅瞅LocalDateTime的toString方法了

public String toString() {
        return date.toString() + 'T' + time.toString();
    }

自定义设置系统日期和时间

public class Test1 {
    public static void main(String[] args) {
        
        LocalDate date1=LocalDate.of(2023,12,22);
        LocalTime time1=LocalTime.of(11,33,35);
        LocalDateTime dateTime1=LocalDateTime.of(date1,time1);
        System.out.println(dateTime1);
    }
}

和上面得到的结果是一样的

2. 单独获取日期时间类中的每个值

获取年份

public class Test2 {
    public static void main(String[] args) {
        //获取年份
        LocalDateTime localDateTime=LocalDateTime.now();
        int year = localDateTime.getYear();
        System.out.println("year = " + year);//2023
    }
}

获取月份-------------此处有需要注意的地方

public class Test2 {
    public static void main(String[] args) {
        LocalDateTime localDateTime=LocalDateTime.now();

        //获取月份
        Month month = localDateTime.getMonth();//枚举类型
        System.out.println("month = " + month);
        //方式一:
        int monthValue = month.getValue();
        System.out.println("monthValue = " + monthValue);
        //方式二:
        int monthValue1 = localDateTime.getMonthValue();
        System.out.println("monthValue1 = " + monthValue1);
    }
}

运行结果:
在这里插入图片描述
可以看到 moth的值为DECEMBER,是枚举类型,我们去瞅一下源码吧

public enum Month implements TemporalAccessor, TemporalAdjuster {

    /**
     * The singleton instance for the month of January with 31 days.
     * This has the numeric value of {@code 1}.
     */
    JANUARY,
    /**
     * The singleton instance for the month of February with 28 days, or 29 in a leap year.
     * This has the numeric value of {@code 2}.
     */
    FEBRUARY,
    /**
     * The singleton instance for the month of March with 31 days.
     * This has the numeric value of {@code 3}.
     */
    MARCH,
    /**
     * The singleton instance for the month of April with 30 days.
     * This has the numeric value of {@code 4}.
     */
    APRIL,
    /**
     * The singleton instance for the month of May with 31 days.
     * This has the numeric value of {@code 5}.
     */
    MAY,
    /**
     * The singleton instance for the month of June with 30 days.
     * This has the numeric value of {@code 6}.
     */
    JUNE,
    /**
     * The singleton instance for the month of July with 31 days.
     * This has the numeric value of {@code 7}.
     */
    JULY,
    /**
     * The singleton instance for the month of August with 31 days.
     * This has the numeric value of {@code 8}.
     */
    AUGUST,
    /**
     * The singleton instance for the month of September with 30 days.
     * This has the numeric value of {@code 9}.
     */
    SEPTEMBER,
    /**
     * The singleton instance for the month of October with 31 days.
     * This has the numeric value of {@code 10}.
     */
    OCTOBER,
    /**
     * The singleton instance for the month of November with 30 days.
     * This has the numeric value of {@code 11}.
     */
    NOVEMBER,
    /**
     * The singleton instance for the month of December with 31 days.
     * This has the numeric value of {@code 12}.
     */
    DECEMBER;
        //获取第几天
        int dayOfMonth = localDateTime.getDayOfMonth();
        System.out.println("dayOfMonth = " + dayOfMonth);

与月份一样的还有星期几 同样是枚举类型

        //获取星期几
        DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
        System.out.println("dayOfWeek = " + dayOfWeek);//FRIDAY
        int dayOfWeekValue = dayOfWeek.getValue();
        System.out.println("dayOfWeekValue = " + dayOfWeekValue);//5
        //获取小时
        int hour = localDateTime.getHour();
        System.out.println("hour = " + hour);
        //获取分钟
        int minute = localDateTime.getMinute();
        System.out.println("minute = " + minute);
        //获取秒钟
        int second = localDateTime.getSecond();
        System.out.println("second = " + second);

3. 使用给定值修改日期

		LocalDate date=LocalDate.now();
        System.out.println("date = " + date);//2023-12-22

        LocalDate date1 = date.withYear(2022);
        System.out.println("date1 = " + date1);//2022-12-22
        LocalDate date2 = date.withMonth(2);
        System.out.println("date2 = " + date2);//2023-02-22
        LocalDate date3 = date.withDayOfMonth(5);
        System.out.println("date3 = " + date3);//2023-12-05
		LocalDate date=LocalDate.now();
        System.out.println("date = " + date);//2023-12-22
 		LocalDate date4 = date.withDayOfMonth(32);
        System.out.println("date4 = " + date4);

此时会报错:因为设置的天数超出范围
在这里插入图片描述

		LocalDate date5 = date.withYear(2021)//修改年份
                .withMonth(6)//修改月份
                .withDayOfMonth(16);//修改天数
        System.out.println("date5 = " + date5);//2021-06-16

4. 设置日期和时间的偏移量

public class Test4 {
    public static void main(String[] args) {
        LocalDate date=LocalDate.now();
        System.out.println("date = " + date);//2023-12-22

        //5天后
        LocalDate date1 = date.plusDays(5);
        System.out.println("date1 = " + date1);//2023-12-27
        //3天前
        LocalDate date2 = date.minusDays(3);
        System.out.println("date2 = " + date2);//2023-12-19
        //1个月之后
        LocalDate date3 = date.plusMonths(1);
        System.out.println("date3 = " + date3);//2024-01-22
        //7个月之前
        LocalDate date4 = date.minusMonths(7);
        System.out.println("date4 = " + date4);//2023-05-22
        //2周之后
        LocalDate date5 = date.plusWeeks(2);
        System.out.println("date5 = " + date5);//2024-01-05
        //3年之前
        LocalDate date6 = date.minusYears(3);
        System.out.println("date6 = " + date6);//2020-12-22
    }
}

5. Instant类

Instant类:代表时间点,获取日期变更子午线
其实这个类和Date类很相似

public class Test5 {
    public static void main(String[] args) {
        //获取当前时间
        LocalDateTime localDateTime=LocalDateTime.now();
        System.out.println("localDateTime = " + localDateTime);

        //获取日期变更子午线时间
        Instant instant=Instant.now();
        System.out.println("instant = " + instant);
    }
}

运行结果:
在这里插入图片描述
我们可以看到,两者的时间表示是一样的,但是得到的时间差8个小时,这是因为Instant类是获取日期变更子午线时间,而我们在东八区呀

获取最大值和最小值

//获取最大值和最小值
        Instant max = Instant.MAX;
        System.out.println("max = " + max);
        Instant min = Instant.MIN;
        System.out.println("min = " + min);

执行结果:
在这里插入图片描述

获取时间戳

//获取时间戳
        long l = instant.toEpochMilli();
        System.out.println("l = " + l);
        System.out.println(System.currentTimeMillis());

执行结果:
在这里插入图片描述
可以看到,这两者得到的时间是一样的

获取北京时间 ---- 具有偏移量的日期时间对象

public class Test5 {
    public static void main(String[] args) {
        //获取当前时间
        LocalDateTime localDateTime=LocalDateTime.now();
        System.out.println("localDateTime = " + localDateTime);

        //获取日期变更子午线时间
        Instant instant=Instant.now();
        System.out.println("instant = " + instant);

		//具有偏移量的日期时间对象
        //获取北京时间
        //方式一:
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));//东八区
        System.out.println("offsetDateTime = " + offsetDateTime);
        //方式二:
        OffsetDateTime offsetDateTime1 = instant.atOffset(ZoneOffset.of("+8"));//东八区
        System.out.println("offsetDateTime1 = " + offsetDateTime1);

    }
}

在这里插入图片描述

将offsetDateTime转为localDateTime
将时间戳转为 Instant对象

//将offsetDateTime转为localDateTime
        Instant instant=Instant.now();
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        LocalDateTime dateTime = offsetDateTime.toLocalDateTime();
        System.out.println("dateTime = " + dateTime);

//将时间戳转为 Instant对象
        Instant instant1 = Instant.ofEpochMilli(System.currentTimeMillis());
        System.out.println("instant1 = " + instant1);//此时拿到的时间是日期变更线的时间

执行结果:
在这里插入图片描述

6. DateTimeFormatter格式化和解析

6.1 将LocalDate转换成字符串String格式

public class Test6 {
    public static void main(String[] args) {
       //将LocalDate转换成字符串String格式
        //1.定义好要转换的格式
        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter formatter1=DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        DateTimeFormatter formatter2=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate date=LocalDate.now();
        LocalDateTime dateTime = LocalDateTime.now();
        //2.进行格式转换
        String s = formatter.format(date);
        String s1 = formatter1.format(date);
        String s2 = formatter2.format(dateTime);
        System.out.println("s = " + s);
        System.out.println("s1 = " + s1);
        System.out.println("s2 = " + s2);
    }
}

运行结果:
在这里插入图片描述

6.2 将时间戳转换成字符串String格式

//将时间戳转换成字符串String格式
        long l = Instant.now().toEpochMilli();
        LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(l)
                , ZoneId.of("Asia/Shanghai"));
        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String s = formatter.format(dateTime);
        System.out.println("s = " + s);//s = 2023-12-23

在转换时,可以发现,需要我们输入时区
那这个时区该怎样获取呢?

获取系统默认时区

        //获取系统默认时区
        ZoneId zoneId = ZoneId.systemDefault();
        System.out.println("zoneId = " + zoneId);//zoneId = Asia/Shanghai

6.3 将字符串解析成日期

        //将字符串解析成日期
        String str="2023-09-25";
        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        LocalDate parse = LocalDate.parse(str, formatter);
        System.out.println("parse = " + parse);

运行上面代码,我们会发现报错了:
在这里插入图片描述
这是因为字符串格式和要解析成的格式不同
这也是我们需要特别注意的地方,两者格式一定要相同才能进行解析
下面是正确的代码:

	//将字符串解析成日期
        String str="2023-09-25";
        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate parse = LocalDate.parse(str, formatter);
        System.out.println("parse = " + parse);

6.4 将字符串解析成日期和时间

//将字符串解析成日期和时间
        String str="2023年09月26日 12:30:40";
        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
        LocalDateTime parse = LocalDateTime.parse(str, formatter);
        System.out.println("parse = " + parse);//parse = 2023-09-26T12:30:40

7. Period类 计算日期之间的间隔

Period类计算两个“日期”之间的间隔,得到的是年月日,假设计算2022年10月1日和2023年9月3日之间相差多少天,得到相差0年11月2天,没有办法知道具体多少天

public class Test7 {
    public static void main(String[] args) {
        LocalDate date1=LocalDate.of(2022,10,1);
        LocalDate date2=LocalDate.of(2023,9,3);
        Period period=Period.between(date1,date2);
        int years = period.getYears();//获取相差年数
        System.out.println("years = " + years);//0   
        System.out.println(period.getMonths());//11   获取相差月数
        System.out.println(period.getDays());//2   获取相差天数
    }
}

如果想知道具体相差多少天,可以使用ChronoUnit类和toEpochDay()方法
但是感觉还是ChronoUnit类好用一点,它是一个枚举类

//计算两个日期相差的天数
        //方法一:
        LocalDate date1=LocalDate.of(2022,10,1);
        LocalDate date2=LocalDate.of(2023,9,3);
        long days = ChronoUnit.DAYS.between(date1, date2);
        System.out.println("days = " + days);//days = 337
        long months = ChronoUnit.MONTHS.between(date1, date2);
        System.out.println("months = " + months);//months = 11
        //方法二:
        long days1 = date2.toEpochDay() - date1.toEpochDay();
        System.out.println("days1 = " + days1);//days1 = 337

8. Duration 计算两个日期时间的间隔

方式一:

public class Test8 {
    public static void main(String[] args) {
        //计算两个日期时间和间隔
        LocalDateTime dateTime=LocalDateTime.of(2023,12,10,12,35,40);
        LocalDateTime now = LocalDateTime.now();
        //计算方式1:
        Duration duration = Duration.between(dateTime, now);
        long days = duration.toDays();
        System.out.println("days = " + days);//13
        long hours = duration.toHours();
        System.out.println("hours = " + hours);//312
        long seconds = duration.toSeconds();
        System.out.println("seconds = " + seconds);//1125091

    }
}

方式二:

		LocalDateTime dateTime=LocalDateTime.of(2022,12,10,12,35,40);
        LocalDateTime now = LocalDateTime.now();

        long years = dateTime.until(now, ChronoUnit.YEARS);
        System.out.println("years = " + years);//1
        long months = dateTime.until(now, ChronoUnit.MONTHS);
        System.out.println("months = " + months);//12
        long days = dateTime.until(now, ChronoUnit.DAYS);
        System.out.println("days = " + days);//378

方式三:

        LocalDateTime dateTime=LocalDateTime.of(1923,12,10,12,35,40);
        LocalDateTime now = LocalDateTime.now();

        long years = ChronoUnit.YEARS.between(dateTime, now);//相差年数
        System.out.println("years = " + years);//100
        long centuries = ChronoUnit.CENTURIES.between(dateTime, now);//相差的世纪
        System.out.println("centuries = " + centuries);//1

9. 时间调节器

//时间调节器 TemporalAdjusters
public class Test9 {
    public static void main(String[] args) {
        LocalDate date=LocalDate.now();

        //获取本周一时间
        LocalDate date1 = date.with(DayOfWeek.MONDAY);
        System.out.println("date1 = " + date1);
        //获取下周一时间
        LocalDate date2 = date.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
        System.out.println("date2 = " + date2);
        //获取本月第一天
        LocalDate date3 = date.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println("date3 = " + date3);
        //获取本月最后一天
        LocalDate date4 = date.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("date4 = " + date4);
        //获取本年第一天
        LocalDate date5 = date.with(TemporalAdjusters.firstDayOfYear());
        System.out.println("date5 = " + date5);
    }
}

10. Date类和LocalDate(LocalTime / LocalDateTime)转换

10.1 LocalDate转Date

public class Test10 {
    public static void main(String[] args) {
        //LocalDate转Date
        LocalDate localDate=LocalDate.now();
        ZonedDateTime zonedDate = localDate.atStartOfDay().atZone(ZoneId.systemDefault());
        Instant instant = zonedDate.toInstant();
        Date date = Date.from(instant);
        String s = new SimpleDateFormat("yyyy-MM-dd").format(date);
        System.out.println("s = " + s);//s = 2023-12-23

    }
}

10.2 LocalDateTime转Date

public class Test10 {
    public static void main(String[] args) {
        //LocalDateTime转Date
        LocalDateTime localDateTime=LocalDateTime.now();
        ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
        Instant instant1 = zonedDateTime.toInstant();

        Date dateTime=Date.from(instant1);
        String s1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dateTime);
        System.out.println("s1 = " + s1);//s1 = 2023-12-23 13:50:42   
    }
}

10.3 Date转LocalDate

public class Test10 {
    public static void main(String[] args) {
        //Date转LocalDate
        Date date=new Date();
        ZonedDateTime zonedDateTime = date.toInstant().atZone(ZoneId.systemDefault());
        LocalDate localDate = zonedDateTime.toLocalDate();
        System.out.println("localDate = " + localDate);//localDate = 2023-12-23
    }
}

10.4 Date转LocalDateTime

public class Test10 {
    public static void main(String[] args) {   
        //Date转LocalDateTime
        Date date=new Date();
        ZonedDateTime zonedDateTime = date.toInstant().atZone(ZoneId.systemDefault());
        LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();
        //localDateTime = 2023-12-23T13:58:07.449
        System.out.println("localDateTime = " + localDateTime);

        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String s = formatter.format(localDateTime);
        // s = 2023-12-23 13:59:17
        System.out.println("s = " + s);
    }
}

文章来源:https://blog.csdn.net/qq_41994691/article/details/134749218
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。