【Java基础教程】(三十七)常用类库篇 · 第七讲:日期时间处理类——三万字全面讲解 LocalDateTime和 DateTimeFormatter,Date、Calendar ~

Java基础教程之常用类库 ·日期时间处理类

  • 1️⃣ 概念
      • 🔍 时间日期及处理类汇总
  • 2️⃣ 优势和缺点
  • 3️⃣ 使用
      • 3.1 各时间日期类使用案例
      • 3.2 各时间日期处理类使用案例
      • 3.3 Date 类
      • 3.4 Calendar 类
      • 3.5 SimpleDateFormat 类
      • 3.6 LocalDateTime 类
      • 3.7 DateTimeFormatter 类
      • 3.8 使用技巧
  • 4️⃣ 应用场景
  • 5️⃣扩展:第三方框架中对日期时间处理的支持
  • 🌾 总结

1️⃣ 概念

Java的时间处理相关类主要是为了提供灵活、可靠地处理日期和时间的能力,以满足各种应用程序中对时间的需求。这些类旨在简化日期和时间的操作,并提供一致的方法和功能来处理时间上的计算、格式化和解析。

🔍 时间日期及处理类汇总

将Java中所有用于表示日期时间的类汇总,罗列如下表:

类名 说明
java.util.Date 提供了日期和时间的基本功能。它表示一个特定的瞬时时间点,但不包含时区信息
java.util.Calendar 为操作日期和时间提供了更高级别的功能,包括日期的计算和格式化。
它支持时区,并且可以进行日期和时间的加减运算
java.util.GregorianCalendar 此类是Calendar的子类,它实现了公历日历系统,支持闰年等功能
java.time.LocalDate Java 8引入的新类,表示不含时间的日期(年、月、日),并且支持大部分常见的日期操作
java.time.LocalTime Java 8引入的新类,用于表示不含日期的时间(小时、分钟、秒),并且支持时间的各种运算
java.time.LocalDateTime 此类是LocalDateLocalTime的组合,用于表示带日期和时间的对象
java.time.ZonedDateTime 表示带时区的日期和时间,可以指定不同的时区
java.time.Duration 用于表示时间间隔的持续时间,精确到小时、分钟等单位
java.time.Period 用于表示日期间隔的周期,精确到年、月、日等单位

以上这些类都是Java标准库中常用的时间处理类,根据具体的需求和场景选择合适的类进行使用。Java 8引入的java.time包更加推荐,提供了更多功能强大且易于使用的日期和时间处理功能。

将日期时间相关处理操作的类汇总,罗列如下表:

类名 说明
java.text.DateFormat 这个抽象类是日期时间格式化的基础。它提供了将日期时间转换为字符串以及将字符串解析为日期时间的方法
java.text.SimpleDateFormat DateFormat的具体实现类,它可以按照指定的模式将日期时间格式化为字符串,也可以将字符串解析为日期时间
java.time.format.DateTimeFormatter Java 8引入的新类,用于格式化和解析日期时间对象。它提供了丰富的模式和选项,以便更灵活地处理不同的日期时间格式
java.util.Formatter 这个类使用格式化字符串和参数,类似于C语言中的printf函数。它可以在输出中插入日期时间,并根据需要进行格式化
java.time.format.FormatStyle 这个枚举类提供了一些预定义的日期、时间和日期时间格式的样式,例如SHORT、MEDIUM、LONG和FULL

以上这些类都提供了丰富的日期时间格式处理功能,可以根据需求选择适合的类来处理日期和时间的格式化和解析操作。其中,Java 8引入的 DateTimeFormatter 是推荐使用的方法,因为它提供了更多的选项和灵活性。

在本文中,主要介绍最常用的DateCalendarSimpleDateFormatLocalDateTimeDateTimeFormatter等类的使用及操作方式等相关知识。而其他类的详细操作方法API等信息,由于篇幅原因本文不再做更多介绍,感兴趣的朋友可私信我一起交流。

  • Date 类:Java 中最基本的日期和时间处理类。它表示一个特定的时间点,以毫秒为单位存储。Date 类有一些基本的方法用于获取、设置日期和时间,但它在处理日期和时间方面存在一些缺陷和限制;

  • Calendar 类:用于表示日历系统。它提供了一些方法来操作日期和时间,如获取年、月、日、时、分、秒等。Calendar 可以将日期和时间字段进行修改,并支持国际化和本地化的日期和时间显示;

  • SimpleDateFormat 类:用于格式化和解析日期和时间的类。可以通过指定模式将 Date 对象格式化为字符串,也可以将字符串解析为 Date 对象;

  • LocalDateTime:Java 8 中的一个类,表示了一个不受时区影响的日期时间对象。它将日期和时间组合在一起,可以精确表示到纳秒级别。相比于传统的Date类,LocalDateTime提供了更多的操作方法和功能。
    使用LocalDateTime类可以进行各种日期和时间相关的操作,例如计算、比较、格式化等。它提供了更直观、简洁和安全的方式来处理日期和时间,避免了以前的一些问题和陷阱,并使开发者能够更轻松地编写健壮和可维护的代码。

  • DateTimeFormatter:Java 8 中的一个类,它提供了日期和时间对象的格式化和解析功能,用于将日期和时间对象转换为字符串或从字符串解析成日期和时间对象。
    它的设计目的是为了弥补旧的日期和时间相关类(如SimpleDateFormat)在线程安全性、易用性和灵活性方面的不足。同时,它引入了新的日期和时间类(例如LocalDateLocalTimeZonedDateTime等),结合了DateTimeFormatter的强大功能,使得处理日期和时间的代码更加简洁和可读,并且适合在多线程环境下使用。

2️⃣ 优势和缺点

  1. Date
  • 优点:简单易懂,可以直接进行日期和时间操作;
  • 缺点:不够灵活,实现上存在线程安全问题
  1. SimpleDateFormat
  • 优点:可以根据指定模式对日期和时间进行格式化和解析
  • 缺点:在多线程环境下不安全
  1. Calendar
  • 优点:可以处理更复杂的日期和时间操作,提供了丰富的方法和功能;
  • 缺点:使用起来较为繁琐,并且性能较差

4. DateTimeFormatter

  • 优点:
    • 可扩展性:支持自定义的模式符号,使开发人员能够创建特定于项目或领域的日期时间格式;
    • 线程安全:线程安全的,可以在多个线程之间共享和重复使用;
    • 预定义模式:包含许多预定义的日期时间格式模式,例如ISO_LOCAL_DATEISO_OFFSET_DATE_TIME等,这些模式可直接使用;
    • 方法丰富:提供了各种方法来处理日期时间对象的格式化、解析、校验和转换。
  • 缺点:
    • 学习曲线:提供了广泛而灵活的选项,这使得学习和理解如何使用它可能需要一些时间和努力。

5. LocalDateTime

  • 优点:
    • 不受时区限制:表示本地日期和时间,不受特定时区的影响。这使得它更适合处理与时区无关的日期和时间操作;
    • 不可变性和线程安全性LocalDateTime是不可变的,任何操作都会返回一个新的实例。这保证了多线程环境下的安全性,并减少了由于修改实例而引起的潜在问题;
    • 解析和格式化:可以使用DateTimeFormatter类将其转换为字符串形式,并从字符串解析为LocalDateTime。这使得数据的输入和输出变得非常方便;
    • 操作丰富:提供了一系列的方法来进行日期和时间的增减、比较、格式化、计算等操作。这使得在处理日期和时间上的常见需求时变得更加便捷。
  • 缺点:
    • 缺乏时区信息:由于LocalDateTime类不包含时区信息,因此在处理需要考虑时区的应用程序中可能不够适用。如果需要处理跨时区的日期和时间,建议使用ZonedDateTime或其他相关类。

3️⃣ 使用

3.1 各时间日期类使用案例

下面是一个Java案例程序,演示如何使用上文各个日期和时间相关类以及对它们的一些简单解释说明:

import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.Duration;
import java.time.Period;

public class DateTimeExample {
    public static void main(String[] args) {
        // 使用java.util.Date获取当前日期和时间
        Date currentDate = new Date();
        System.out.println("当前日期和时间: " + currentDate);

        // 使用java.util.Calendar获取当前日期
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;  // 注意:Calendar中月份是从0开始计数的,所以需要加1
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println("当前日期: " + year + "-" + month + "-" + dayOfMonth);

        // 使用java.util.GregorianCalendar创建指定日期和时间的对象
        GregorianCalendar gregorianCalendar = new GregorianCalendar(2022, 0, 1, 12, 30, 0);  // 2022年1月1日 12:30:00
        Date specificDate = gregorianCalendar.getTime();
        System.out.println("指定日期和时间: " + specificDate);

        // 使用java.time.LocalDate获取当前日期
        LocalDate localDate = LocalDate.now();
        System.out.println("当前日期: " + localDate);

        // 使用java.time.LocalTime获取当前时间
        LocalTime localTime = LocalTime.now();
        System.out.println("当前时间: " + localTime);

        // 使用java.time.LocalDateTime获取当前日期和时间
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("当前日期和时间: " + localDateTime);

        // 使用java.time.ZonedDateTime获取带时区的日期和时间
        ZonedDateTime zonedDateTime = ZonedDateTime.now();
        System.out.println("当前带时区的日期和时间: " + zonedDateTime);

        // 使用java.time.Duration计算时间间隔
        Duration duration = Duration.between(localTime, LocalTime.of(14, 30));
        long hours = duration.toHours();
        long minutes = duration.toMinutes() % 60;
        System.out.println("当前时间与今天14:30之间的时间间隔: " + hours + "小时" + minutes + "分钟");

        // 使用java.time.Period计算日期间隔
        Period period = Period.between(localDate, LocalDate.of(2023, 12, 31));
        int years = period.getYears();
        int months = period.getMonths();
        int days = period.getDays();
        System.out.println("当前日期与2023年12月31日之间的日期间隔: " + years + "年" + months + "月" + days + "日");
    }
}

以上的案例程序演示了如何使用这些类来获取当前日期和时间、创建特定的日期和时间对象,以及计算日期和时间之间的间隔。

运行结果如下:

当前日期和时间: Mon Jun 26 17:26:27 CST 2023
当前日期: 2023-6-26
指定日期和时间: Sat Jan 01 12:30:00 CST 2022
当前日期: 2023-06-26
当前时间: 17:26:28.114
当前日期和时间: 2023-06-26T17:26:28.114
当前带时区的日期和时间: 2023-06-26T17:26:28.122+08:00[Asia/Shanghai]
当前时间与今天14:30之间的时间间隔: -2小时-56分钟
当前日期与2023年12月31日之间的日期间隔: 0年6月5日

3.2 各时间日期处理类使用案例

下面是一个Java案例程序,演示如何使用上文各个日期和时间相关处理操作类以及对它们的一些简单解释说明:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;

public class FormattingExample {
    public static void main(String[] args) {
        Date date = new Date();
        // 使用 java.text.DateFormat 格式化日期和时间
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG, Locale.US);
        String formattedDate = dateFormat.format(date);
        System.out.println("格式化的日期:" + formattedDate);

        // 使用 java.text.SimpleDateFormat 自定义日期和时间格式化
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = simpleDateFormat.format(date);
        System.out.println("自定义格式化的日期和时间:" + formattedDateTime);

        // 使用 java.time.format.DateTimeFormatter 格式化日期和时间
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedLocalDateTime = LocalDateTime.now().format(dateTimeFormatter);
        System.out.println("使用 DateTimeFormatter 格式化的当前日期和时间:" + formattedLocalDateTime);

        // 使用 java.util.Formatter 进行格式化
        Formatter formatter = new Formatter();
        String formattedString = formatter.format("Hello, %s! Today is %tF.", "John", date).toString();
        System.out.println("使用 Formatter 进行格式化:" + formattedString);
        formatter.close();

        // 使用 java.time.format.FormatStyle 定义预定义的格式风格
        String formattedStyleDateTime = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).format(LocalDateTime.now());
        System.out.println("使用 FormatStyle 定义的格式风格:" + formattedStyleDateTime);
    }
}

上述案例程序演示了如何使用这些类和方法来格式化日期和时间,包括使用预定义风格、自定义格式化模式等。运行结果如下:

格式化的日期:June 26, 2023
自定义格式化的日期和时间:2023-06-26 17:40:52
使用 DateTimeFormatter 格式化的当前日期和时间:2023-06-26 17:40:53
使用 Formatter 进行格式化:Hello, John! Today is 2023-06-26.
使用 FormatStyle 定义的格式风格:2023-6-26 17:40:53

3.3 Date 类

Java的Date类是一个用于处理日期和时间的基本类,它提供了一系列方法来操纵和显示日期、时间和相关信息。下面是Java Date类的全部操作方法API:

类型 方法 说明
构造函数 Date() 使用当前系统日期和时间创建一个Date对象
Date(long date) 使用给定的毫秒数从1970年1月1日开始创建一个Date对象
获取日期和时间信息 getTime() 返回自 1970 年 1 月 1 日至当前时间的毫秒数差值
getYear() 获取表示年份的值(从1900开始),已废弃(deprecated)
getMonth() 获取表示月份的值(范围为0-11)
getDate() 获取表示日期的值
getDay() 获取表示星期几的值(范围为0-6,其中0代表星期日)
getHours() 获取小时数(24小时制)
getMinutes() 获取分钟数
getSeconds() 获取秒数
设置日期和时间信息 setTime(long time) 设置日期对象的毫秒数
setYear(int year) 设置年份(从1900开始),已废弃(deprecated)
setMonth(int month) 设置月份(范围为0-11)
setDate(int date) 设置日期
setHours(int hours) 设置小时数(24小时制)
setMinutes(int minutes) 设置分钟数
setSeconds(int seconds) 设置秒数
其他操作方法 before(Date when) 检查日期对象是否在给定日期之前
after(Date when) 检查日期对象是否在给定日期之后
equals(Object obj) 比较两个日期对象是否相等
clone() 创建并返回日期对象的拷贝
toString() 将日期对象转换为字符串表示形式

下面是一个演示如何使用Date类的Java案例程序,包含了代码注释说明:

import java.util.Date;

public class DateExample {
    public static void main(String[] args) {
        // 使用无参构造函数创建一个Date对象,表示当前系统日期和时间
        Date currentDate = new Date();
        System.out.println("Current Date: " + currentDate);

        // 使用指定的毫秒数创建一个Date对象,表示从1970年1月1日开始的特定时间点
        long milliseconds = 1636382593000L;
        Date specificDate = new Date(milliseconds);
        System.out.println("Specific Date: " + specificDate);

        // 获取日期和时间信息

        // 返回自 1970 年 1 月 1 日至当前时间的毫秒数差值
        long timeDifference = currentDate.getTime();
        System.out.println("Time difference (milliseconds): " + timeDifference);

        // 获取表示年份的值(从1900开始)
        int year = currentDate.getYear();
        System.out.println("Year: " + (year + 1900));

        // 获取表示月份的值(范围为0-11)
        int month = currentDate.getMonth() + 1;
        System.out.println("Month: " + month);

        // 获取表示日期的值
        int date = currentDate.getDate();
        System.out.println("Date: " + date);

        // 获取表示星期几的值(范围为0-6,其中0代表星期日)
        int dayOfWeek = currentDate.getDay();
        System.out.println("Day of week: " + dayOfWeek);

        // 获取小时数(24小时制)
        int hours = currentDate.getHours();
        System.out.println("Hours: " + hours);

        // 获取分钟数
        int minutes = currentDate.getMinutes();
        System.out.println("Minutes: " + minutes);

        // 获取秒数
        int seconds = currentDate.getSeconds();
        System.out.println("Seconds: " + seconds);

        // 设置日期和时间信息

        // 设置日期对象的毫秒数
        specificDate.setTime(System.currentTimeMillis());
        System.out.println("Updated Specific Date: " + specificDate);

        // 设置年份(从1900开始)
        specificDate.setYear(122);
        System.out.println("Updated Specific Date (Year): " + specificDate);

        // 设置月份(范围为0-11)
        specificDate.setMonth(10);
        System.out.println("Updated Specific Date (Month): " + specificDate);

        // 设置日期
        specificDate.setDate(8);
        System.out.println("Updated Specific Date (Date): " + specificDate);

        // 设置小时数(24小时制)
        specificDate.setHours(15);
        System.out.println("Updated Specific Date (Hours): " + specificDate);

        // 设置分钟数
        specificDate.setMinutes(30);
        System.out.println("Updated Specific Date (Minutes): " + specificDate);

        // 设置秒数
        specificDate.setSeconds(45);
        System.out.println("Updated Specific Date (Seconds): " + specificDate);

        // 其他操作方法

        // 检查日期对象是否在给定日期之前
        boolean before = currentDate.before(specificDate);
        System.out.println("Is current date before specific date? " + before);

        // 检查日期对象是否在给定日期之后
        boolean after = specificDate.after(currentDate);
        System.out.println("Is specific date after current date? " + after);

        // 比较两个日期对象是否相等
        boolean equals = currentDate.equals(specificDate);
        System.out.println("Are the two dates equal? " + equals);

        // 创建并返回日期对象的拷贝
        Date copy = (Date) specificDate.clone();
        System.out.println("Copy of specific date: " + copy);

        // 将日期对象转换为字符串表示形式
        String dateString = specificDate.toString();
        System.out.println("Specific date as string: " + dateString);
    }
}

运行结果如下:

Current Date: Mon Jun 26 19:51:15 CST 2023
Specific Date: Mon Nov 08 22:43:13 CST 2021
Time difference (milliseconds): 1687780275710
Year: 2023
Month: 6
Date: 26
Day of week: 1
Hours: 19
Minutes: 51
Seconds: 15
Updated Specific Date: Mon Jun 26 19:51:15 CST 2023
Updated Specific Date (Year): Sun Jun 26 19:51:15 CST 2022
Updated Specific Date (Month): Sat Nov 26 19:51:15 CST 2022
Updated Specific Date (Date): Tue Nov 08 19:51:15 CST 2022
Updated Specific Date (Hours): Tue Nov 08 15:51:15 CST 2022
Updated Specific Date (Minutes): Tue Nov 08 15:30:15 CST 2022
Updated Specific Date (Seconds): Tue Nov 08 15:30:45 CST 2022
Is current date before specific date? false
Is specific date after current date? false
Are the two dates equal? false
Copy of specific date: Tue Nov 08 15:30:45 CST 2022
Specific date as string: Tue Nov 08 15:30:45 CST 2022

3.4 Calendar 类

Java的Calendar类是用于日期和时间处理的重要类之一,它提供了丰富的操作方法来对日期进行增减、比较以及格式化等操作。下面是Java Calendar类的全部操作方法API的介绍:

类型 方法 说明
获取日期和时间信息 get(int field) 返回给定字段(field)的值,例如Calendar.YEAR表示年份,Calendar.MONTH表示月份,Calendar.DAY_OF_MONTH表示日期等
getTime() 返回表示当前时间的一个Date对象
getTimeInMillis() 返回表示当前时间的一个时间戳,以毫秒为单位
getActualMaximum(int field) 返回指定字段(field)的最大允许值
getActualMinimum(int field) 返回指定字段(field)的最小允许值
getDisplayName(int field, int style, Locale locale) 返回指定字段(field)的本地化名称。可以根据所需的语言环境(Locale)和样式(style)获取字段的可读名称
设置日期和时间信息 set(int field, int value) 设置给定字段(field)的值为指定的值(value)
add(int field, int amount) 将指定字段(field)的值增加指定的数量(amount)。可以实现对日期和时间的增减操作
setTime(Date date) 将对象的值设置为给定日期(Date)所代表的时间
roll(int field, boolean up) 将指定字段(field)的值“滚动”,即在不改变更大字段的情况下增减指定字段的值
其他操作方法 before(Object when) 检查当前对象表示的时间是否在给定时间之前
after(Object when) 检查当前对象表示的时间是否在给定时间之后
compareTo(Calendar anotherCalendar) 比较两个对象的时间顺序。返回值为负数、零或正数,表示当前对象时间在另一个对象时间之前、相同或之后
clear() 清除所有字段的值,将Calendar对象重置为初始状态
isSet(int field) 检查指定字段(field)是否已设置为具体值

以下是一个使用Java Calendar 类全部操作方法API的案例程序,代码都有解释说明:

import java.util.Calendar;
import java.util.Date;

public class CalendarExample {
    public static void main(String[] args) {
        // 创建一个Calendar实例
        Calendar calendar = Calendar.getInstance();

        // get(int field): 返回给定字段的值
        int year = calendar.get(Calendar.YEAR);
        System.out.println("当前年份: " + year);

        int month = calendar.get(Calendar.MONTH);
        System.out.println("当前月份: " + (month + 1)); // 月份从0开始,所以要加1

        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println("今天是本月的第几天: " + dayOfMonth);

        // set(int field, int value): 设置给定字段的值
        calendar.set(Calendar.YEAR, 2022);
        System.out.println("修改后的年份: " + calendar.get(Calendar.YEAR));

        // add(int field, int amount): 将指定字段的值增加指定的数量
        calendar.add(Calendar.MONTH, 2);
        System.out.println("两个月后的月份: " + (calendar.get(Calendar.MONTH) + 1));

        // getTime(): 返回表示当前Calendar对象的时间戳,即Date对象
        Date date = calendar.getTime();
        System.out.println("当前日期时间: " + date);

        // getTimeInMillis(): 返回表示当前Calendar对象的时间戳,以毫秒为单位
        long timestamp = calendar.getTimeInMillis();
        System.out.println("当前时间戳: " + timestamp);

        // setTime(Date date): 将Calendar对象的值设置为给定日期所代表的时间
        Date newDate = new Date();
        calendar.setTime(newDate);
        System.out.println("修改后的日期时间: " + calendar.getTime());

        // getActualMaximum(int field): 返回指定字段的最大允许值
        int maxMonth = calendar.getActualMaximum(Calendar.MONTH);
        System.out.println("当前年份最大的月份是: " + (maxMonth + 1));

        // getActualMinimum(int field): 返回指定字段的最小允许值
        int minMonth = calendar.getActualMinimum(Calendar.MONTH);
        System.out.println("当前年份最小的月份是: " + (minMonth + 1));

        // before(Object when): 检查当前Calendar对象表示的时间是否在给定时间之前
        Calendar comparisonCalendar = Calendar.getInstance();
        comparisonCalendar.set(Calendar.YEAR, 2022);
        boolean isBefore = calendar.before(comparisonCalendar);
        System.out.println("当前日期时间是否在2022年之前: " + isBefore);

        // after(Object when): 检查当前Calendar对象表示的时间是否在给定时间之后
        boolean isAfter = calendar.after(comparisonCalendar);
        System.out.println("当前日期时间是否在2022年之后: " + isAfter);

        // compareTo(Calendar anotherCalendar): 比较两个Calendar对象的时间顺序
        int comparisonResult = calendar.compareTo(comparisonCalendar);
        System.out.println("当前日期时间与指定日期时间的比较结果: " + comparisonResult);

        // clear(): 清除所有字段的值,将Calendar对象重置为初始状态
        calendar.clear();
        System.out.println("清除后的年份: " + calendar.get(Calendar.YEAR));

        // getDisplayName(int field, int style, Locale locale): 返回指定字段的本地化名称
        String monthName = calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, java.util.Locale.getDefault());
        System.out.println("当前月份的本地化名称: " + monthName);

        // isSet(int field): 检查指定字段是否已设置为具体值
        boolean isYearSet = calendar.isSet(Calendar.YEAR);
        System.out.println("年份字段是否已设置: " + isYearSet);

        // roll(int field, boolean up): 将指定字段的值“滚动”,即在不改变更大字段的情况下增减指定字段的值
        calendar.set(Calendar.DAY_OF_MONTH, 31); // 设置为一个月的最后一天
        calendar.roll(Calendar.DAY_OF_MONTH, false); // 减少一个月的天数,而不影响月份
        System.out.println("一个月前的日期: " + calendar.getTime());
    }
}

运行结果如下:

当前年份: 2023
当前月份: 6
今天是本月的第几天: 26
修改后的年份: 2022
两个月后的月份: 8
当前日期时间: Fri Aug 26 20:47:49 CST 2022
当前时间戳: 1661518069288
修改后的日期时间: Mon Jun 26 20:47:49 CST 2023
当前年份最大的月份是: 12
当前年份最小的月份是: 1
当前日期时间是否在2022年之前: false
当前日期时间是否在2022年之后: true
当前日期时间与指定日期时间的比较结果: 1
清除后的年份: 1970
当前月份的本地化名称: 一月
年份字段是否已设置: true
一个月前的日期: Fri Jan 30 00:00:00 CST 1970

3.5 SimpleDateFormat 类

SimpleDateFormat类用于将日期对象转换为字符串(格式化),或将字符串解析为日期对象,并根据指定的模式进行日期和时间的格式化与解析。它提供了一系列方法来设置、获取和操作日期格式、时区以及相关符号信息等。通过使用这些方法,我们可以灵活地处理不同格式的日期和时间数据。

注意:在使用SimpleDateFormat类进行日期和时间的格式化和解析时,请确保模式字符串(pattern)的正确性,否则可能会导致意外的结果或错误的解析。模式字符串中的特殊字符必须按照规定的方式使用,例如yyyy表示四位年份,MM表示两位月份等。详细的模式字符含义可以参考Java官方文档中的具体说明。

同时,请注意SimpleDateFormat类不是线程安全的,如果在多线程环境中使用,请采取适当的同步措施。

下面是Java SimpleDateFormat类的全部操作方法API的介绍:

方法 描述
SimpleDateFormat(String pattern) 创建一个新的SimpleDateFormat对象,使用指定的模式
void applyLocalizedPattern(String pattern) 将给定的本地化模式应用于此日期格式
void applyPattern(String pattern) 将给定的模式应用于此日期格式
String format(Date date) 根据此日期格式将给定的日期对象格式化为字符串,并返回结果
Date parse(String source) 将给定的字符串解析为日期对象,根据此日期格式的规则
void setLenient(boolean lenient) 指定解析过程是否宽松。如果为true,则解析过程中会尽量接受不严格匹配的输入。如果为false,则只能接受严格匹配的输入(默认为true
boolean isLenient() 返回解析过程是否宽松的设置
void setTimeZone(TimeZone zone) 设置此日期格式的时区
TimeZone getTimeZone() 返回此日期格式的时区
void setCalendar(Calendar newCalendar) 设置与此日期格式关联的日历
Calendar getCalendar() 返回与此日期格式关联的日历
String toPattern() 返回此日期格式的字符串表示形式
String toLocalizedPattern() 返回此日期格式的本地化字符串表示形式
DateFormatSymbols getDateFormatSymbols() 返回日期格式的符号信息,例如星期几名称、月份名称等
void setDateFormatSymbols(DateFormatSymbols newFormatSymbols) 设置日期格式的符号信息

以下是一个使用SimpleDateFormat类的全部操作方法的Java案例程序,代码都有解释说明:

import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class SimpleDateFormatExample {
    public static void main(String[] args) {
        Date now = new Date();

        // 创建一个新的SimpleDateFormat对象,使用指定的模式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 根据此日期格式将给定的日期对象格式化为字符串,并返回结果
        String format = dateFormat.format(now);
        System.out.println("格式化的当前日期时间: " + format);

        // 将给定的本地化模式应用于此日期格式
        dateFormat.applyLocalizedPattern("HH时mm分ss秒");
        format = dateFormat.format(now);
        System.out.println("本地化模式格式化的当前日期时间: " + format);

        // 将给定的模式应用于此日期格式
        dateFormat.applyPattern("yyyyMMddHHmmss");
        format = dateFormat.format(now);
        System.out.println("给定的模式格式化的当前日期时间: " +format);

        // 将给定的字符串解析为日期对象,根据此日期格式的规则
        String dateString = "20220103120000";
        try {
            Date parsedDate = dateFormat.parse(dateString);
            System.out.println("解析得到的日期对象: " + parsedDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 指定解析过程是否宽松
        dateFormat.setLenient(false);

        // 返回解析过程是否宽松的设置
        boolean isLenient = dateFormat.isLenient();
        System.out.println("解析过程是否宽松: " + isLenient);

        // 设置此日期格式的时区
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+2"));
        System.out.println("时区: " + dateFormat.getTimeZone().getID());

        // 设置与此日期格式关联的日历
        Calendar calendar = Calendar.getInstance();
        dateFormat.setCalendar(calendar);
        System.out.println("关联的日历: " + dateFormat.getCalendar().getTime());

        // 返回此日期格式的字符串表示形式
        String pattern = dateFormat.toPattern();
        System.out.println("日期格式的字符串表示形式: " + pattern);

        // 返回此日期格式的本地化字符串表示形式
        String localizedPattern = dateFormat.toLocalizedPattern();
        System.out.println("日期格式的本地化字符串表示形式: " + localizedPattern);

        // 返回日期格式的符号信息,例如星期几名称、月份名称等
        DateFormatSymbols symbols = dateFormat.getDateFormatSymbols();
        String[] months = symbols.getMonths();
        System.out.println("月份名称: " + months[calendar.get(Calendar.MONTH)]);

        // 设置日期格式的符号信息
        DateFormatSymbols newSymbols = new DateFormatSymbols();
        newSymbols.setMonths(new String[]{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"});
        dateFormat.setDateFormatSymbols(newSymbols);

        months = dateFormat.getDateFormatSymbols().getMonths();
        System.out.println("新月份名称: " + months[calendar.get(Calendar.MONTH)]);
    }
}

这个例子演示了如何使用SimpleDateFormat类的全部操作方法。通过实例化SimpleDateFormat对象并调用相应的方法,我们可以根据指定的模式将日期对象格式化为字符串,或者解析给定的字符串为日期对象。

程序中还演示了如何设置和获取时区、日历、模式字符串以及日期格式的符号信息等。
运行结果如下:

格式化的当前日期时间: 2023-06-26 21:36:41
本地化模式格式化的当前日期时间: 21时36分41秒
给定的模式格式化的当前日期时间: 20230626213641
解析得到的日期对象: Mon Jan 03 12:00:00 CST 2022
解析过程是否宽松: false
时区: GMT+02:00
关联的日历: Mon Jun 26 21:36:41 CST 2023
日期格式的字符串表示形式: yyyyMMddHHmmss
日期格式的本地化字符串表示形式: aaaannjjHHmmss
月份名称: 六月
新月份名称: June

3.6 LocalDateTime 类

下面是LocalDateTime 类的全部操作方法API及其说明:

类型 方法 描述
创建LocalDateTime对象 now() 返回当前日期时间
now(ZoneId zone) 返回指定时区的当前日期时间
now(Clock clock) 使用指定时钟对象返回当前日期时间
of(int year, Month month, int dayOfMonth, int hour, int minute) 创建指定日期时间的对象
of(LocalDate date, LocalTime time) 根据指定的日期和时间创建对象
parse(CharSequence text) 将指定字符串解析为对象
获取信息 LocalDate toLocalDate() 返回日期部分
LocalTime toLocalTime() 返回时间部分
int getYear() 返回年份
Month getMonth() 返回月份
int getMonthValue() 返回月份值
int getDayOfMonth() 返回月份中的天数
int getHour() 返回小时数
int getMinute() 返回分钟数
int getSecond() 返回秒数
int getNano() 返回纳秒数
boolean isAfter(LocalDateTime other) 检查当前日期时间是否在指定日期时间之后
boolean isBefore(LocalDateTime other) 检查当前日期时间是否在指定日期时间之前
boolean isEqual(LocalDateTime other) 检查当前日期时间是否与指定日期时间相等
加减操作 plusYears(long years) 将指定的年数加到当前日期时间
plusMonths(long months) 将指定的月数加到当前日期时间
plusWeeks(long weeks) 将指定的周数加到当前日期时间
plusDays(long days) 将指定的天数加到当前日期时间
plusHours(long hours) 将指定的小时数加到当前日期时间
plusMinutes(long minutes) 将指定的分钟数加到当前日期时间
plusSeconds(long seconds) 将指定的秒数加到当前日期时间
plusNanos(long nanos) 将指定的纳秒数加到当前日期时间
minusYears(long years) 将指定的年数从当前日期时间中减去
minusMonths(long months) 将指定的月数从当前日期时间中减去
minusWeeks(long weeks) 将指定的周数从当前日期时间中减去
minusDays(long days) 将指定的天数从当前日期时间中减去
minusHours(long hours) 将指定的小时数从当前日期时间中减去
minusMinutes(long minutes) 将指定的分钟数从当前日期时间中减去
minusSeconds(long seconds) 将指定的秒数从当前日期时间中减去
minusNanos(long nanos) 将指定的纳秒数从当前日期时间中减去
其他操作 boolean isSupported(TemporalField field) 检查指定字段是否支持日期时间
String format(DateTimeFormatter formatter) 将日期时间格式化为字符串
boolean isSupported(ChronoUnit unit) 检查指定单位是否支持日期时间间隔计算
long until(Temporal endExclusive, TemporalUnit unit) 计算当前日期时间与指定日期时间之间的时间间隔

这个表格列出了LocalDateTime类的全部操作方法,包括创建对象、获取日期时间部分、比较、加减日期时间值、格式化输出以及时间间隔计算等。你可以根据具体需求选择适合的方法来操作LocalDateTime对象。

下面是一个使用LocalDateTime类的操作方法的示例程序,演示了如何使用其中的一些常用方法:

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;

public class LocalDateTimeExample {
    public static void main(String[] args) {
        // 返回当前日期时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        System.out.println("当前日期时间: " + currentDateTime);

        // 返回指定时区的当前日期时间
        LocalDateTime dateTimeInZone = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
        System.out.println("指定时区的当前日期时间: " + dateTimeInZone);

        // 使用指定时钟对象返回当前日期时间
        Clock clock = Clock.systemDefaultZone();
        LocalDateTime dateTimeWithClock = LocalDateTime.now(clock);
        System.out.println("使用指定时钟对象返回当前日期时间: " + dateTimeWithClock);

        // 创建指定日期时间的对象
        LocalDateTime customDateTime = LocalDateTime.of(2022, Month.JUNE, 15, 10, 30);
        System.out.println("创建指定日期时间的对象: " + customDateTime);

        // 根据指定的日期和时间创建对象
        LocalDate date = LocalDate.of(2022, Month.JUNE, 15);
        LocalTime time = LocalTime.of(10, 30);
        LocalDateTime dateTimeFromParts = LocalDateTime.of(date, time);
        System.out.println("根据指定的日期和时间创建对象: " + dateTimeFromParts);

        // 将指定字符串解析为对象
        String dateString = "2022-06-15 10:30:00";
        LocalDateTime parsedDateTime = LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println("解析后的日期时间: " + parsedDateTime);

        // 获取信息
        LocalDate localDate = dateTimeFromParts.toLocalDate();
        System.out.println("日期部分: " + localDate);

        LocalTime localTime = dateTimeFromParts.toLocalTime();
        System.out.println("时间部分: " + localTime);

        int year = dateTimeFromParts.getYear();
        System.out.println("年份: " + year);

        Month month = dateTimeFromParts.getMonth();
        System.out.println("月份: " + month);

        int monthValue = dateTimeFromParts.getMonthValue();
        System.out.println("月份值: " + monthValue);

        int dayOfMonth = dateTimeFromParts.getDayOfMonth();
        System.out.println("月份中的天数: " + dayOfMonth);

        int hour = dateTimeFromParts.getHour();
        System.out.println("小时数: " + hour);

        int minute = dateTimeFromParts.getMinute();
        System.out.println("分钟数: " + minute);

        int second = dateTimeFromParts.getSecond();
        System.out.println("秒数: " + second);

        int nano = dateTimeFromParts.getNano();
        System.out.println("纳秒数: " + nano);


        // 创建一个指定的日期时间
        LocalDateTime comparisonDateTime = LocalDateTime.of(2022, 6, 15, 12, 0, 0);
        // 检查当前日期时间是否在指定日期时间之后
        boolean isAfter = currentDateTime.isAfter(comparisonDateTime);
        if (isAfter) {
            System.out.println("当前日期时间在指定日期时间之后");
        } else {
            System.out.println("当前日期时间在指定日期时间之前或相同");
        }

        // 加减操作
        LocalDateTime plusYears = dateTimeFromParts.plusYears(1);
        System.out.println("加1年后的日期时间: " + plusYears);

        LocalDateTime minusMonths = dateTimeFromParts.minusMonths(2);
        System.out.println("减去2个月后的日期时间: " + minusMonths);

        // 其他操作
        boolean isSupported = dateTimeFromParts.isSupported(ChronoField.DAY_OF_WEEK);
        System.out.println("是否支持星期字段: " + isSupported);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = dateTimeFromParts.format(formatter);
        System.out.println("格式化后的日期时间: " + formattedDateTime);

        boolean isSupportedUnit = dateTimeFromParts.isSupported(ChronoUnit.HOURS);
        System.out.println("是否支持小时单位计算: " + isSupportedUnit);

        LocalDateTime futureDateTime = LocalDateTime.of(2023, Month.DECEMBER, 31, 23, 59);
        long daysUntilFutureDate = currentDateTime.until(futureDateTime, ChronoUnit.DAYS);
        System.out.println(currentDateTime + "与 "+ futureDateTime +" 之间的天数间隔: " + daysUntilFutureDate);
    }
}

该示例程序演示了如何使用LocalDateTime类的各种操作方法。运行程序结果如下:

当前日期时间: 2023-06-26T22:12:10.751
指定时区的当前日期时间: 2023-06-26T22:12:10.751
使用指定时钟对象返回当前日期时间: 2023-06-26T22:12:10.751
创建指定日期时间的对象: 2022-06-15T10:30
根据指定的日期和时间创建对象: 2022-06-15T10:30
解析后的日期时间: 2022-06-15T10:30
日期部分: 2022-06-15
时间部分: 10:30
年份: 2022
月份: JUNE
月份值: 6
月份中的天数: 15
小时数: 10
分钟数: 30
秒数: 0
纳秒数: 0
当前日期时间在指定日期时间之后
加1年后的日期时间: 2023-06-15T10:30
减去2个月后的日期时间: 2022-04-15T10:30
是否支持星期字段: true
格式化后的日期时间: 2022-06-15 10:30:00
是否支持小时单位计算: true
2023-06-26T22:12:10.751与 2023-12-31T23:59 之间的天数间隔: 188

3.7 DateTimeFormatter 类

下面是DateTimeFormatter类的全部操作方法API及其说明:

类型 方法 说明
创建DateTimeFormatter对象 ofPattern(String pattern) 使用指定的模式字符串创建对象
ofLocalizedDateTime(FormatStyle dateTimeStyle) 创建一个本地化日期时间格式的对象
ofLocalizedDateTime(FormatStyle dateStyle, FormatStyle timeStyle) 创建一个本地化日期时间格式的对象,并指定日期部分和时间部分的显示样式
ISO_LOCAL_DATE 预定义的日期格式(yyyy-MM-dd)的对象
ISO_LOCAL_TIME 预定义的时间格式(HH:mm:ss.SSS)的对象
ISO_LOCAL_DATE_TIME 预定义的日期时间格式(yyyy-MM-dd’T’HH:mm:ss.SSS)的对象
withLocale(Locale locale) 返回一个新的对象,其中的地区设置为指定的地区
withDecimalStyle(DecimalStyle decimalStyle) 返回一个新的对象,其中的格式设置为指定的十进制样式
withResolverStyle(ResolverStyle resolverStyle) 返回一个新的对象,其中的解析方式设置为指定的解析方式
其他操作 parse(CharSequence text) 将字符串解析为TemporalAccessor对象(例如LocalDateLocalTimeLocalDateTime等)
format(TemporalAccessor temporal) 将指定的TemporalAccessor对象格式化为字符串
getDecimalStyle() 返回该DateTimeFormatter对象使用的十进制样式
getResolverStyle() 返回该DateTimeFormatter对象的解析方式

下面是一个使用DateTimeFormatter类的操作方法的示例程序,演示了如何使用其中的一些方法:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DecimalStyle;
import java.time.format.FormatStyle;
import java.time.format.ResolverStyle;
import java.util.Locale;

public class DateTimeFormatterExample {
    public static void main(String[] args) {
        // 使用指定的模式字符串创建对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.now();
        String formattedDateTime = dateTime.format(formatter);
        System.out.println("格式化后的日期时间: " + formattedDateTime);


        // 创建一个本地化日期时间格式的对象
        DateTimeFormatter localizedFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        String localizedFormattedDateTime = dateTime.format(localizedFormatter);
        System.out.println("本地化格式化后的日期时间: " + localizedFormattedDateTime);


        // 创建一个本地化日期时间格式的对象,并指定日期部分和时间部分的显示样式
        localizedFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT);
        String localizedCustomFormattedDateTime = dateTime.format(localizedFormatter);
        System.out.println("指定日期时间样式的本地化格式化后的日期时间: " + localizedCustomFormattedDateTime);


        // 预定义的日期、时间和日期时间格式
        DateTimeFormatter dateFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
        DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_LOCAL_TIME;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        String formattedDate = dateTime.format(dateFormatter);
        String formattedTime = dateTime.format(timeFormatter);
        String formattedDateTime2 = dateTime.format(dateTimeFormatter);
        System.out.println("预定义的日期格式化结果: " + formattedDate);
        System.out.println("预定义的时间格式化结果: " + formattedTime);
        System.out.println("预定义的日期时间格式化结果: " + formattedDateTime2);


        // 返回一个新的对象,其中的地区设置为指定的地区
        DateTimeFormatter withLocaleFormatter = dateTimeFormatter.withLocale(Locale.CHINA);
        String formattedWithLocaleDateTime = dateTime.format(withLocaleFormatter);
        System.out.println("指定地区的格式化后的日期时间: " + formattedWithLocaleDateTime);


        // 返回一个新的对象,其中的格式设置为指定的十进制样式
        DateTimeFormatter withDecimalStyleFormatter = withLocaleFormatter.withDecimalStyle(DateTimeFormatter.ISO_TIME.getDecimalStyle());
        String formattedWithDecimalStyleDateTime = dateTime.format(withDecimalStyleFormatter);
        System.out.println("指定十进制样式的格式化后的日期时间: " + formattedWithDecimalStyleDateTime);


        // 返回一个新的对象,其中的解析方式设置为指定的解析方式
        DateTimeFormatter withResolverStyleFormatter = withDecimalStyleFormatter.withResolverStyle(DateTimeFormatter.ISO_DATE.getResolverStyle());
        String date = "2022-06-15T10:30:00.484";
        LocalDateTime parsedDateTime = LocalDateTime.parse(date, withResolverStyleFormatter);
        System.out.println("严格解析后的日期时间: " + parsedDateTime);


        // 将字符串解析为TemporalAccessor对象(例如LocalDate、LocalTime或LocalDateTime等)
        String dateString = "2022-06-15";
        LocalDate parsedDate = LocalDate.parse(dateString, dateFormatter);
        System.out.println("解析后的日期: " + parsedDate);


        // 将指定的TemporalAccessor对象格式化为字符串
        LocalDateTime localDateTime = LocalDateTime.of(2022, 6, 15, 10, 30);
        String formattedCustomDateTime = localDateTime.format(formatter);
        System.out.println("自定义日期时间格式化结果: " + formattedCustomDateTime);


        // 返回该DateTimeFormatter对象使用的十进制样式
        DecimalStyle decimalStyle = withResolverStyleFormatter.getDecimalStyle();
        System.out.println("该DateTimeFormatter对象使用的十进制样式: " + decimalStyle);


        // 返回该DateTimeFormatter对象的解析方式
        ResolverStyle resolverStyle = withResolverStyleFormatter.getResolverStyle();
        System.out.println("该DateTimeFormatter对象的解析方式: " + resolverStyle);
    }
}

程序运行结果如下:

格式化后的日期时间: 2023/06/26 22:38:28
本地化格式化后的日期时间: 2023年6月26日 下午10时38分28秒
指定日期时间样式的本地化格式化后的日期时间: 2023-6-26 下午10:38
预定义的日期格式化结果: 2023-06-26
预定义的时间格式化结果: 22:38:28.126
预定义的日期时间格式化结果: 2023-06-26T22:38:28.126
指定地区的格式化后的日期时间: 2023-06-26T22:38:28.126
指定十进制样式的格式化后的日期时间: 2023-06-26T22:38:28.126
严格解析后的日期时间: 2022-06-15T10:30:00.484
解析后的日期: 2022-06-15
自定义日期时间格式化结果: 2022/06/15 10:30:00
该DateTimeFormatter对象使用的十进制样式: DecimalStyle[0+-.]
该DateTimeFormatter对象的解析方式: STRICT

3.8 使用技巧

为了更好地使用Java的时间处理相关类,以下是一些使用技巧:

  • 尽量使用java.time包代替旧的日期类:Java 8引入了新的日期和时间API,位于java.time包中,它们提供了更好的设计和功能;
  • 使用线程安全的类:如果需要在多线程环境中使用日期和时间类,建议使用线程安全的类,如Instant、LocalDateTime等;
  • 谨慎使用旧的Date和Calendar类:由于它们的局限性和不足,使用上需谨慎并注意线程安全问题。

4️⃣ 应用场景

Java的时间处理相关类适用于各种应用场景,包括但不限于以下几个常见场景:

  1. 日期和时间计算:Java的时间处理类可以用于执行各种日期和时间的计算操作。例如,你可以使用LocalDateLocalDateTime类来增加或减少天数、月份、年份以及其他日期部分。

  2. 日期和时间格式化和解析:Java的时间处理类提供了强大的日期和时间格式化和解析功能。你可以使用DateTimeFormatter类来将日期对象转换为指定格式的字符串,并可以将字符串解析为日期对象。

  3. 日期和时间比较和排序:通过使用Java的时间处理类,可以方便地比较和排序日期和时间。你可以使用compareTo方法进行比较,以确定一个日期是在另一个日期之前、之后还是相等。

  4. 跨时区操作:Java的时间处理类支持跨时区的操作。你可以使用ZoneId类和ZonedDateTime类来管理和转换不同时区的日期和时间。

  5. 定时任务调度:Java的时间处理类可以与定时任务调度器结合使用,例如Spring框架中的Cron表达式触发器或JavaSE中的Timer类,以实现定时任务的调度和触发。

总而言之,Java的时间处理相关类适用于广泛的应用场景,包括日期和时间的计算、格式化和解析、比较和排序、跨时区操作、定时任务调度、数据库持久化以及业务逻辑中的日期计算等。无论你是开发桌面应用、Web应用还是后端系统,Java的时间处理类都提供了丰富的功能和方法,方便处理各种日期和时间操作需求。

5️⃣扩展:第三方框架中对日期时间处理的支持

Spring框架提供了多种对Java日期时间处理的工具类支持。下面列出了Spring中一些常用的日期时间处理相关的类和模块:

  1. org.springframework.format.datetime.DateFormatter:日期格式化器,用于将日期对象转换为字符串、字符串转换为日期对象。

  2. org.springframework.format.annotation.DateTimeFormat:日期时间格式注解,用于指定特定字段或方法参数的日期时间格式。

  3. org.springframework.util.DateUtils:日期时间工具类,提供了各种日期操作的静态辅助方法,例如日期比较、格式化、解析等。

  4. org.springframework.scheduling.support.CronTrigger:基于Cron表达式的触发器,可以使用Cron表达式定义定时任务的执行规则,灵活控制任务的调度时间。

除了这些类和模块,Spring还通过整合其他第三方日期时间处理库,如Joda-Time和java.time(JSR-310),为应用程序提供更强大的日期时间处理功能。Spring在不同的模块中提供了对这些库的集成和支持,例如在Spring Boot中,可以轻松配置和使用Java 8日期时间API或Joda-Time。

除了Spring框架,还有一些其他流行的Java框架提供对日期时间处理的工具类支持。以下是其中几个常用的框架:

  1. Apache Commons Lang:Apache Commons Lang是一个通用的Java工具库,提供了许多实用的工具类和方法。它包含DateUtilsFastDateFormat等类,用于日期时间的解析、格式化和操作。

  2. Joda-Time:Joda-Time是一个非常流行的日期时间处理库,在Java 8之前被广泛使用。它提供了丰富的日期时间类和方法,如DateTimeLocalDatePeriod等,以及灵活的日期时间操作和计算功能。

  3. ThreeTen-Extra:ThreeTen-Extra是在Java 8日期时间API基础上构建的扩展库。它提供了额外的日期时间类和工具,如季度、年账、时间间隔计算等功能。

这些框架提供了不同程度和不同特点的日期时间处理工具类支持,可以根据具体需求选择适合的框架。无论是处理基本的日期比较和格式化,还是执行复杂的日期计算和跨时区操作,这些框架都能满足各种应用场景的需求。

🌾 总结

本文介绍了Java日期时间处理类的概念,以及它们在日期和时间操作中的优势和缺点。我们讨论了Java提供的一些主要日期时间处理类,包括DateCalendarSimpleDateFormatLocalDateTimeDateTimeFormatter等。我们分析了它们的使用方法,并提供了一些使用案例和技巧。

这些Java日期时间处理类提供了丰富的功能和灵活性,使得我们可以方便地执行日期和时间的计算、格式化、解析和比较。然而,每个类都有自己的特点和适用范围。例如,Date类在早期被广泛使用,但它的缺点也逐渐显现出来,不推荐作为首选。LocalDateTimeDateTimeFormatter则是Java 8引入的新API,提供了更方便和优雅的方式来处理日期和时间。

在应用场景方面,Java的日期时间处理类适用于各种应用需求。我们可以将其用于日期和时间计算、格式化和解析、跨时区操作、定时任务调度、数据库持久化以及业务逻辑中的日期计算等。这些类提供了强大的功能和方法,能够满足不同项目的日期时间处理需求。

最后,我们提到了一些第三方框架,如Spring和Apache Commons Lang,它们也提供了对Java日期时间处理的支持。这些框架通过整合其他库或提供自己实现的工具类,进一步增强了日期时间处理的功能和灵活性。

综上所述,Java日期时间处理类提供了丰富的工具和方法来处理各种日期时间操作。无论是开发桌面应用、Web应用还是后端系统,Java的日期时间处理类都能满足不同场景和需求,让开发人员更轻松地处理日期时间相关任务。



温习回顾上一篇(点击跳转)

《【Java基础教程】(三十六)常用类库篇 · 第六讲:数学运算类——全面讲解Java数学计算支持类库,BigDecimal、Math、Random、DecimalFormat…~》



继续阅读下一篇(点击跳转)

《【Java基础教程】(三十八)常用类库篇 · 第八讲:数组操作类——解析Arrays类中的全部操作方法,解锁Java数组操作技巧~》

版权声明:本文为博主作者:小山code原创文章,版权归属原作者,如果侵权,请联系我们删除!

原文链接:https://blog.csdn.net/LVSONGTAO1225/article/details/131401077

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2024年4月10日
下一篇 2024年4月10日

相关推荐