JAVA从零开始19_常用API 日期和时间

本文详细介绍了Java中处理日期和时间的API,包括Date、SimpleDateFormat、Calendar等传统API,以及JDK8新增的日期时间类,如LocalDate、LocalTime、ZonedDateTime等。文章通过实例展示了各API的常用方法和应用场景,强调了Java 8新日期时间API的优势和推荐使用。

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

一、Date

Java中的Date类是一个表示特定瞬间的时间,精确到毫秒的类。它位于java.util包中。然而,在Java 8及以后的版本中,建议使用java.time包下的新的日期和时间API(如LocalDateLocalTimeLocalDateTime等),因为它们提供了更强大且易于使用的功能。

尽管如此,我们仍然可以讨论一下Date类中的一些常用方法:

  1. Date():构造一个表示当前日期和时间的Date对象。

  2. Date(long date):构造一个根据指定毫秒数初始化的Date对象。

  3. getTime():返回自1970年1月1日0点0分0秒(UTC)以来的毫秒数。

  4. setTime(long time):设置时间,使用自1970年1月1日0点0分0秒(UTC)以来的毫秒数。

  5. toString():将Date对象转换为一个包含日期和时间信息的字符串。

  6. compareTo(Date anotherDate):比较两个日期。返回值小于、等于或大于零,表示此日期分别早于、等于或晚于指定的日期。

  7. equals(Object obj):比较两个Date对象是否相等。

  8. before(Date when):检查此日期是否在指定日期之前。

  9. after(Date when):检查此日期是否在指定日期之后。

以下是一些使用Java Date类的示例应用场景:

  1. 记录事件时间戳:
    在日志记录或事件追踪中,我们可能需要记录事件发生的时间。可以使用Date类来表示这个时间戳。
Date eventTimestamp = new Date();
  1. 测量代码执行时间:
    我们可以在代码执行前后分别创建Date对象,然后比较它们的时间差来测量代码执行时间。
Date startTime = new Date();
// Code to be measured
Date endTime = new Date();
long elapsedTime = endTime.getTime() - startTime.getTime();
System.out.println("Elapsed time in milliseconds: " + elapsedTime);
  1. 与遗留代码或第三方库集成:
    在某些情况下,可能需要与使用Date类的遗留代码或第三方库集成。在这种情况下,我们可能需要创建、处理和传递Date对象。

  2. java.sql.Datejava.sql.Timestamp进行转换:
    在使用JDBC处理数据库时,可能需要将java.util.Date转换为java.sql.Datejava.sql.Timestamp,以便将日期和时间数据存储在数据库中。

// Convert java.util.Date to java.sql.Date
java.util.Date utilDate = new Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

// Convert java.util.Date to java.sql.Timestamp
java.util.Date utilDate2 = new Date();
java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(utilDate2.getTime());

请注意,尽管这些场景中仍然可以使用Date类,但在Java 8及更高版本中,使用新的日期和时间API(如InstantDurationLocalDateLocalTime等)可能会更加灵活和强大。


二、SimpleDateFormat

Java中的SimpleDateFormat类是一个用于对Date对象进行格式化和解析的类。它是java.text.DateFormat的一个具体子类,位于java.text包中。通过使用特定的模式,可以将Date对象转换为人类可读的字符串,或将字符串解析为Date对象。

以下是SimpleDateFormat类中一些常用方法的概述:

  1. SimpleDateFormat(String pattern):根据给定的模式构造一个新的SimpleDateFormat对象。模式是一个字符串,包含代表日期和时间元素的特殊字符。例如,yyyy-MM-dd HH:mm:ss表示年-月-日 时:分:秒。

  2. format(Date date):将给定的Date对象格式化为一个字符串,使用此SimpleDateFormat对象的模式。

  3. parse(String source):尝试将给定的字符串解析为一个Date对象,使用此SimpleDateFormat对象的模式。如果解析成功,返回一个Date对象;如果解析失败,抛出ParseException异常。

  4. setTimeZone(TimeZone zone):为此SimpleDateFormat对象设置时区。这将影响formatparse方法的结果。

  5. setLenient(boolean lenient):设置解析过程是否宽松。如果设置为true,解析器将尽量解释不完全符合模式的字符串;如果设置为false,解析器将严格按照模式解析字符串。

以下是一个简单的示例,展示如何使用SimpleDateFormat类:

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

public class Main {
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // Format a Date object to a string
        Date currentDate = new Date();
        String formattedDate = sdf.format(currentDate);
        System.out.println("Formatted date: " + formattedDate);

        // Parse a string to a Date object
        String dateString = "2023-04-21 12:30:00";
        try {
            Date parsedDate = sdf.parse(dateString);
            System.out.println("Parsed date: " + parsedDate);
        } catch (ParseException e) {
            System.err.println("Error parsing date: " + e.getMessage());
        }
    }
}

在这个示例中,我们创建了一个SimpleDateFormat对象,使用模式yyyy-MM-dd HH:mm:ss,然后分别演示了如何使用format方法将Date对象格式化为字符串,以及如何使用parse方法将字符串解析为Date对象。

以下是一些使用SimpleDateFormat类的示例应用场景:

  1. 将日期和时间转换为特定格式的字符串:
    当需要以特定格式显示日期和时间时,可以使用SimpleDateFormat类将Date对象转换为所需格式的字符串。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currentDate = new Date();
String formattedDate = sdf.format(currentDate);
System.out.println("Formatted date: " + formattedDate);
  1. 从特定格式的字符串解析日期和时间:
    当从文本文件、数据库或用户输入中接收日期和时间字符串时,可以使用SimpleDateFormat类将字符串解析为Date对象。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = "2023-04-21";
try {
    Date parsedDate = sdf.parse(dateString);
    System.out.println("Parsed date: " + parsedDate);
} catch (ParseException e) {
    System.err.println("Error parsing date: " + e.getMessage());
}
  1. 将日期和时间转换为适合文件名的格式:
    当将日期和时间用作文件名的一部分时,可以使用SimpleDateFormat类将Date对象转换为适合文件名的格式。
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
Date currentDate = new Date();
String formattedDateForFilename = sdf.format(currentDate);
String filename = "report_" + formattedDateForFilename + ".txt";
System.out.println("Filename: " + filename);
  1. 从一个时区转换为另一个时区:
    SimpleDateFormat类可以用于在不同时区之间转换日期和时间。
String dateString = "2023-04-21 12:30:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// Parse the date string to a Date object
Date date = sdf.parse(dateString);

// Convert the date to another timezone
TimeZone sourceTimeZone = TimeZone.getTimeZone("UTC");
TimeZone targetTimeZone = TimeZone.getTimeZone("Asia/Shanghai");
sdf.setTimeZone(sourceTimeZone);
long sourceTimeInMillis = date.getTime();
long targetTimeInMillis = sourceTimeInMillis + targetTimeZone.getOffset(sourceTimeInMillis) - sourceTimeZone.getOffset(sourceTimeInMillis);
Date targetDate = new Date(targetTimeInMillis);

System.out.println("Source date: " + sdf.format(date));
System.out.println("Target date: " + sdf.format(targetDate));

请注意,虽然SimpleDateFormat类在Java中广泛使用,但Java 8及以后版本中的新日期和时间API(如DateTimeFormatterLocalDateLocalTime等)提供了更强大、灵活且线程安全的日期和时间处理方法。如果可能,建议使用新的日期和时间API。


三、Calendar

Java中的Calendar类是一个抽象基类,用于处理日期和时间。它位于java.util包中,提供了丰富的方法来处理日期和时间的计算。Calendar类的一个具体实现是GregorianCalendar,它表示了格里高利历(国际上广泛使用的公历)。

以下是Calendar类中一些常用方法的概述:

  1. getInstance():返回一个表示当前日期和时间的Calendar实例,使用默认时区和区域设置。

  2. getInstance(TimeZone zone):返回一个表示当前日期和时间的Calendar实例,使用指定的时区和默认区域设置。

  3. get(int field):返回给定字段的值。例如,calendar.get(Calendar.YEAR)将返回当前年份。

  4. set(int field, int value):设置给定字段的值。例如,calendar.set(Calendar.MONTH, Calendar.JANUARY)将把月份设置为1月。

  5. add(int field, int amount):根据给定的数量增加或减少给定字段的值。例如,calendar.add(Calendar.DAY_OF_MONTH, 7)将把日期向前推进7天。

  6. getTime():返回表示此Calendar实例的日期和时间的Date对象。

  7. setTime(Date date):使用给定的Date对象设置此Calendar实例的时间。

  8. before(Object when):判断此Calendar实例的时间是否在指定对象表示的时间之前。

  9. after(Object when):判断此Calendar实例的时间是否在指定对象表示的时间之后。

以下是一个简单的示例,展示如何使用Calendar类:

import java.util.Calendar;

public class Main {
    public static void main(String[] args) {
        // Get the current date and time
        Calendar calendar = Calendar.getInstance();
        System.out.println("Current date: " + calendar.getTime());

        // Set the year, month, and day
        calendar.set(Calendar.YEAR, 2023);
        calendar.set(Calendar.MONTH, Calendar.APRIL);
        calendar.set(Calendar.DAY_OF_MONTH, 21);
        System.out.println("New date: " + calendar.getTime());

        // Add 5 days to the date
        calendar.add(Calendar.DAY_OF_MONTH, 5);
        System.out.println("5 days later: " + calendar.getTime());

        // Get the day of the week
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        System.out.println("Day of the week: " + dayOfWeek);
    }
}

在这个示例中,我们使用getInstance()方法创建了一个表示当前日期和时间的Calendar对象,然后使用set()方法设置了年、月、日,并使用add()方法向日期添加了几天。我们还使用get()方法获取了星期几的值。

以下是一些使用Calendar类的示例应用场景:

  1. 获取当前日期和时间:
    使用getInstance()方法创建一个表示当前日期和时间的Calendar对象。
Calendar calendar = Calendar.getInstance();
System.out.println("Current date and time: " + calendar.getTime());
  1. 获取和设置日期的各个部分:
    可以使用get()set()方法来获取和设置日期的年、月、日、小时、分钟和秒等部分。
Calendar calendar = Calendar.getInstance();

// Get the current year, month, and day
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);

// Set the year, month, and day
calendar.set(Calendar.YEAR, 2023);
calendar.set(Calendar.MONTH, Calendar.APRIL);
calendar.set(Calendar.DAY_OF_MONTH, 21);
  1. 日期的加减操作:
    可以使用add()方法来对日期的某个部分进行加减操作,例如向日期添加或减去几天、几个月或几年。
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 5); // Add 5 days to the current date
calendar.add(Calendar.MONTH, -2); // Subtract 2 months from the current date
  1. 比较两个日期:
    可以使用before()after()方法来比较两个Calendar对象表示的日期。
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar2.add(Calendar.DAY_OF_MONTH, 1);

if (calendar1.before(calendar2)) {
    System.out.println("calendar1 is before calendar2");
} else if (calendar1.after(calendar2)) {
    System.out.println("calendar1 is after calendar2");
} else {
    System.out.println("calendar1 is equal to calendar2");
}
  1. 计算特定日期的星期几:
    可以使用get()方法获取特定日期的星期几。
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2023);
calendar.set(Calendar.MONTH, Calendar.APRIL);
calendar.set(Calendar.DAY_OF_MONTH, 21);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
System.out.println("Day of the week: " + dayOfWeek);

虽然Calendar类在Java中被广泛使用,但Java 8及以后版本中的新日期和时间API(如LocalDateLocalTimeLocalDateTime等)提供了更强大、灵活且线程安全的日期和时间处理方法。如果可能,建议使用新的日期和时间API。


四、JDK8新增时间类

在JDK 8之前,Java中处理日期和时间的主要类是DateCalendar。这些类存在一些问题,如不直观的API、可变性导致的线程安全问题、性能低下等。为了解决这些问题,JDK 8引入了新的日期和时间API,这些API遵循JSR-310规范,提供了更强大、灵活且线程安全的日期和时间处理方法。

以下是JDK 8新增日期和时间类的原因:

  1. 不可变性:新的日期和时间API中的核心类,如LocalDateLocalTimeLocalDateTime,都是不可变的。这意味着它们在创建后不能被修改,从而使得在多线程环境中使用它们更加安全。

  2. 清晰的API:新API提供了更清晰、更直观的方法和命名,使得编写和阅读与日期和时间相关的代码变得更容易。例如,plusDays()minusHours()等方法比较直观地描述了它们的功能。

  3. 附加功能:新API提供了一些附加功能,如日期和时间的计算、格式化、解析等,这些功能在旧API中不易实现或缺失。

  4. 易于使用:新API提供了许多实用方法,如获取当前日期、时间、日期时间,以及更容易地进行日期和时间的操作(例如,加减天数、月份等)。

  5. 区域设置和时区支持:新API提供了对区域设置和时区的更好支持,如ZoneIdZonedDateTime等类,使处理不同时区的日期和时间变得更简单。

  6. 性能:新API的设计更注重性能,例如,由于类是不可变的,可以在多线程环境中安全地共享它们,减少了创建新对象的开销。

总之,JDK 8引入了新的日期和时间API,以解决旧API的问题,并提供更强大、灵活且线程安全的日期和时间处理方法。新API的使用更加直观,易于理解,提高了开发人员的生产力。

以下是JDK 8新增的一些日期和时间类及其常见用途:

  1. LocalDate:表示一个不带时间的日期,通常用于表示生日、纪念日等。它提供了一系列方法来处理日期,如获取当前日期、加减天数、月份等。

  2. LocalTime:表示一天中的时间(不包含日期),通常用于表示一个特定时间点。它提供了一系列方法来处理时间,如获取当前时间、加减小时、分钟等。

  3. LocalDateTime:表示一个不带时区的日期和时间,通常用于表示具体的日期和时间。它提供了一系列方法来处理日期和时间,如获取当前日期时间、加减天数、小时等。

  4. Instant:表示一个时间戳,用于表示从1970年1月1日0时0分0秒(UTC)开始的时间偏移量。它通常用于计算两个时间点之间的差异。

  5. Period:表示两个日期之间的时间段,以年、月、日为单位。它可以用来计算日期的差异。

  6. Duration:表示两个时间点之间的时间段,以秒和纳秒为单位。它可以用来计算时间的差异。

  7. ZoneId:表示一个时区,通常用于处理不同地区的日期和时间。

  8. ZonedDateTime:表示一个带时区的日期和时间,通常用于处理全球范围内的日期和时间。

  9. DateTimeFormatter:用于格式化和解析日期和时间。它可以与LocalDateLocalTimeLocalDateTimeZonedDateTime等类一起使用,将日期和时间转换为特定格式的字符串,或将字符串解析为日期和时间。

这些类为处理日期和时间提供了强大、灵活且线程安全的方法。相比之下,旧的DateCalendar类的API不够直观且存在线程安全问题。


五、Instant

Instant类表示一个时间戳,用于表示从1970年1月1日0时0分0秒(UTC)开始的时间偏移量。它位于java.time包中,主要用于处理时间戳和计算两个时间点之间的差异。以下是Instant类的一些常用方法:

  1. now():获取当前时间的Instant对象。
Instant now = Instant.now();
System.out.println("Current timestamp: " + now);
  1. ofEpochSecond(long epochSecond):根据给定的以秒为单位的Unix时间戳创建一个Instant对象。
Instant fromEpochSecond = Instant.ofEpochSecond(1629357712L);
System.out.println("Instant from epoch second: " + fromEpochSecond);
  1. ofEpochMilli(long epochMilli):根据给定的以毫秒为单位的Unix时间戳创建一个Instant对象。
Instant fromEpochMilli = Instant.ofEpochMilli(1629357712000L);
System.out.println("Instant from epoch milli: " + fromEpochMilli);
  1. plus(Duration duration)minus(Duration duration):给当前Instant对象加上或减去一个Duration,返回一个新的Instant对象。
Instant now = Instant.now();
Duration duration = Duration.ofHours(3);
Instant plusThreeHours = now.plus(duration);
Instant minusThreeHours = now.minus(duration);
System.out.println("Current timestamp: " + now);
System.out.println("Plus 3 hours: " + plusThreeHours);
System.out.println("Minus 3 hours: " + minusThreeHours);
  1. until(Temporal endExclusive, TemporalUnit unit):计算当前Instant对象和另一个Instant对象之间的时间差(以指定的时间单位表示)。
Instant start = Instant.now();
// Simulate a delay
Thread.sleep(2000);
Instant end = Instant.now();

long millisElapsed = start.until(end, ChronoUnit.MILLIS);
System.out.println("Milliseconds elapsed: " + millisElapsed);
  1. isBefore(Instant otherInstant)isAfter(Instant otherInstant):比较当前Instant对象和另一个Instant对象的时间顺序。
Instant instant1 = Instant.now();
Instant instant2 = instant1.plusSeconds(10);

if (instant1.isBefore(instant2)) {
    System.out.println("instant1 is before instant2");
} else if (instant1.isAfter(instant2)) {
    System.out.println("instant1 is after instant2");
} else {
    System.out.println("instant1 is equal to instant2");
}

Instant类常用于记录事件发生的时间戳、计算两个时间点之间的时间差、比较时间戳等场景。请注意,Instant类不包含时区信息,因此在处理需要考虑时区的场景时,您可能需要使用其他类,如ZonedDateTime


六、ZonedDateTime

ZonedDateTime类表示一个带时区的日期和时间,位于java.time包中。它在处理需要考虑时区的场景时非常有用。以下是ZonedDateTime类的一些常用方法和使用场景:

  1. now():获取当前时区的ZonedDateTime对象。
ZonedDateTime now = ZonedDateTime.now();
System.out.println("Current date and time with timezone: " + now);
  1. now(ZoneId zone):获取指定时区的ZonedDateTime对象。
ZoneId zoneId = ZoneId.of("Asia/Shanghai");
ZonedDateTime nowInShanghai = ZonedDateTime.now(zoneId);
System.out.println("Current date and time in Shanghai: " + nowInShanghai);
  1. of(LocalDate date, LocalTime time, ZoneId zone):根据给定的LocalDateLocalTimeZoneId创建一个ZonedDateTime对象。
LocalDate date = LocalDate.of(2023, Month.APRIL, 21);
LocalTime time = LocalTime.of(10, 30);
ZoneId zoneId = ZoneId.of("Asia/Shanghai");
ZonedDateTime zonedDateTime = ZonedDateTime.of(date, time, zoneId);
System.out.println("ZonedDateTime from LocalDate, LocalTime and ZoneId: " + zonedDateTime);
  1. plus(Duration duration)minus(Duration duration):给当前ZonedDateTime对象加上或减去一个Duration,返回一个新的ZonedDateTime对象。
ZonedDateTime now = ZonedDateTime.now();
Duration duration = Duration.ofHours(3);
ZonedDateTime plusThreeHours = now.plus(duration);
ZonedDateTime minusThreeHours = now.minus(duration);
System.out.println("Current date and time with timezone: " + now);
System.out.println("Plus 3 hours: " + plusThreeHours);
System.out.println("Minus 3 hours: " + minusThreeHours);
  1. withZoneSameInstant(ZoneId targetZone):将当前ZonedDateTime对象转换为目标时区的ZonedDateTime对象,同时保持时间戳不变。
ZonedDateTime now = ZonedDateTime.now();
ZoneId targetZone = ZoneId.of("Asia/Shanghai");
ZonedDateTime converted = now.withZoneSameInstant(targetZone);
System.out.println("Current date and time with timezone: " + now);
System.out.println("Converted to target timezone: " + converted);
  1. format(DateTimeFormatter formatter):使用DateTimeFormatterZonedDateTime对象格式化为字符串。
ZonedDateTime now = ZonedDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss VV");
String formatted = now.format(formatter);
System.out.println("Formatted date and time with timezone: " + formatted);

ZonedDateTime类的使用场景包括处理全球范围内的日期和时间、转换时区、计算带时区的日期和时间之间的时间差等。当需要处理带时区的日期和时间时,建议使用ZonedDateTime类。


七、DateTimeFormatter

DateTimeFormatter类位于java.time.format包中,用于格式化和解析日期和时间。以下是DateTimeFormatter类的一些常用方法和使用场景:

  1. ofPattern(String pattern):根据给定的格式化模式字符串创建一个DateTimeFormatter对象。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  1. format(TemporalAccessor temporal):将给定的TemporalAccessor(如LocalDateLocalTimeLocalDateTimeZonedDateTime等)格式化为字符串。
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted = formatter.format(now);
System.out.println("Formatted date and time: " + formatted);
  1. parse(CharSequence text):根据DateTimeFormatter对象的格式化模式,将给定的字符串解析为一个TemporalAccessor对象。通常,您需要将TemporalAccessor对象转换为具体的日期和时间类型,如LocalDateLocalTimeLocalDateTimeZonedDateTime
String dateTimeString = "2023-04-21 10:30:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeString, formatter);
System.out.println("Parsed date and time: " + parsedDateTime);
  1. BASIC_ISO_DATEISO_LOCAL_DATEISO_LOCAL_TIMEISO_LOCAL_DATE_TIME等预定义格式:DateTimeFormatter类提供了一些预定义的格式化模式,可直接用于格式化和解析日期和时间。
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
String formatted = isoFormatter.format(now);
System.out.println("Formatted date and time using ISO_LOCAL_DATE_TIME: " + formatted);

DateTimeFormatter类的使用场景包括:

  • 将日期和时间对象(如LocalDateLocalTimeLocalDateTimeZonedDateTime)格式化为字符串,以便进行展示、存储或传输。
  • 将字符串解析为日期和时间对象,以便进行进一步的操作,如计算日期和时间的差异、进行日期和时间的加减等。

DateTimeFormatter类为处理日期和时间的格式化和解析提供了强大而灵活的方法。使用它可以轻松地将日期和时间对象转换为特定格式的字符串,或将字符串解析为日期和时间对象。


八、LocalDate

LocalDate类位于java.time包中,表示一个不带时间的日期。以下是LocalDate类的一些常用方法和使用场景:

  1. now():获取当前日期的LocalDate对象。
LocalDate today = LocalDate.now();
System.out.println("Today's date: " + today);
  1. of(int year, Month month, int dayOfMonth):根据给定的年份、月份和日期创建一个LocalDate对象。
LocalDate birthday = LocalDate.of(1995, Month.AUGUST, 25);
System.out.println("Birthday: " + birthday);
  1. plusDays(long days)plusWeeks(long weeks)plusMonths(long months)plusYears(long years):在当前日期的基础上加上给定的天数、周数、月数或年数,返回一个新的LocalDate对象。
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plusDays(1);
LocalDate nextWeek = today.plusWeeks(1);
LocalDate nextMonth = today.plusMonths(1);
LocalDate nextYear = today.plusYears(1);
System.out.println("Today: " + today);
System.out.println("Tomorrow: " + tomorrow);
System.out.println("Next week: " + nextWeek);
System.out.println("Next month: " + nextMonth);
System.out.println("Next year: " + nextYear);
  1. minusDays(long days)minusWeeks(long weeks)minusMonths(long months)minusYears(long years):在当前日期的基础上减去给定的天数、周数、月数或年数,返回一个新的LocalDate对象。
LocalDate today = LocalDate.now();
LocalDate yesterday = today.minusDays(1);
LocalDate lastWeek = today.minusWeeks(1);
LocalDate lastMonth = today.minusMonths(1);
LocalDate lastYear = today.minusYears(1);
System.out.println("Today: " + today);
System.out.println("Yesterday: " + yesterday);
System.out.println("Last week: " + lastWeek);
System.out.println("Last month: " + lastMonth);
System.out.println("Last year: " + lastYear);
  1. getDayOfWeek():获取当前LocalDate对象表示的日期是星期几。
LocalDate today = LocalDate.now();
DayOfWeek dayOfWeek = today.getDayOfWeek();
System.out.println("Today is: " + dayOfWeek);
  1. isBefore(LocalDate other)isAfter(LocalDate other):比较当前LocalDate对象和另一个LocalDate对象的日期顺序。
LocalDate today = LocalDate.now();
LocalDate anotherDate = LocalDate.of(1995, Month.AUGUST, 25);

if (today.isBefore(anotherDate)) {
    System.out.println("Today is before anotherDate");
} else if (today.isAfter(anotherDate)) {
    System.out.println("Today is after anotherDate");
} else {
    System.out.println("Today is equal to anotherDate");
}
  1. daysBetween(LocalDate startDate, LocalDate endDate):计算两个LocalDate对象之间的天数差。要使用此方法,需要先引入java.time.temporal.ChronoUnit类。
LocalDate startDate = LocalDate.of(2023, Month.APRIL,
user: 继续
assistant: 21);
LocalDate endDate = LocalDate.of(2023, Month.MAY, 5);
long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
System.out.println("Days between startDate and endDate: " + daysBetween);

LocalDate类的使用场景包括:

  • 处理不需要时间信息的日期,如生日、纪念日等。
  • 计算两个日期之间的天数差。
  • 在日期基础上进行加减操作。
  • 比较两个日期的顺序。

在处理不涉及时间和时区的日期场景时,可以使用LocalDate类进行操作。它提供了丰富的方法来完成日期相关的操作和计算。


九、 LocalTime和LocalDateTime

LocalTimeLocalDateTime类位于java.time包中,LocalTime表示一个不带日期的时间,LocalDateTime表示一个不带时区的日期和时间。以下是这两个类的一些常用方法和使用场景:

LocalTime

  1. now():获取当前时间的LocalTime对象。
LocalTime currentTime = LocalTime.now();
System.out.println("Current time: " + currentTime);
  1. of(int hour, int minute)of(int hour, int minute, int second):根据给定的小时、分钟(和秒)创建一个LocalTime对象。
LocalTime time1 = LocalTime.of(10, 30);
LocalTime time2 = LocalTime.of(10, 30, 45);
System.out.println("Time1: " + time1);
System.out.println("Time2: " + time2);
  1. plusHours(long hours)plusMinutes(long minutes)plusSeconds(long seconds):在当前时间的基础上加上给定的小时数、分钟数或秒数,返回一个新的LocalTime对象。
LocalTime currentTime = LocalTime.now();
LocalTime plusTwoHours = currentTime.plusHours(2);
LocalTime plusThirtyMinutes = currentTime.plusMinutes(30);
System.out.println("Current time: " + currentTime);
System.out.println("Plus 2 hours: " + plusTwoHours);
System.out.println("Plus 30 minutes: " + plusThirtyMinutes);
  1. minusHours(long hours)minusMinutes(long minutes)minusSeconds(long seconds):在当前时间的基础上减去给定的小时数、分钟数或秒数,返回一个新的LocalTime对象。
LocalTime currentTime = LocalTime.now();
LocalTime minusTwoHours = currentTime.minusHours(2);
LocalTime minusThirtyMinutes = currentTime.minusMinutes(30);
System.out.println("Current time: " + currentTime);
System.out.println("Minus 2 hours: " + minusTwoHours);
System.out.println("Minus 30 minutes: " + minusThirtyMinutes);

LocalDateTime

  1. now():获取当前日期和时间的LocalDateTime对象。
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("Current date and time: " + currentDateTime);
  1. of(LocalDate date, LocalTime time):根据给定的LocalDateLocalTime对象创建一个LocalDateTime对象。
LocalDate date = LocalDate.of(2023, Month.APRIL, 21);
LocalTime time = LocalTime.of(10, 30);
LocalDateTime dateTime = LocalDateTime.of(date, time);
System.out.println("Date and time: " + dateTime);
  1. plusDays(long days)plusHours(long hours)plusMinutes(long minutes)plusSeconds(long seconds):在当前日期和时间的基础上加上给定的天数、小时数、分钟数或秒数,返回一个新的LocalDateTime对象。
LocalDateTime currentDateTime = LocalDateTime.now();
LocalDateTime plusTwoDaysAndThreeHours = currentDateTime.plusDays(2).plusHours(3);
System.out.println("Current date and time: " + currentDateTime);
System.out.println("Plus 2 days and 3 hours: " + plusTwoDaysAndThreeHours);
  1. minusDays user: 继续 assistant: (long days)minusHours(long hours)minusMinutes(long minutes)minusSeconds(long seconds):在当前日期和时间的基础上减去给定的天数、小时数、分钟数或秒数,返回一个新的LocalDateTime对象。
LocalDateTime currentDateTime = LocalDateTime.now();
LocalDateTime minusTwoDaysAndThreeHours = currentDateTime.minusDays(2).minusHours(3);
System.out.println("Current date and time: " + currentDateTime);
System.out.println("Minus 2 days and 3 hours: " + minusTwoDaysAndThreeHours);
  1. toLocalDate():从LocalDateTime对象中提取LocalDate对象。
LocalDateTime currentDateTime = LocalDateTime.now();
LocalDate currentDate = currentDateTime.toLocalDate();
System.out.println("Current date and time: " + currentDateTime);
System.out.println("Extracted date: " + currentDate);
  1. toLocalTime():从LocalDateTime对象中提取LocalTime对象。
LocalDateTime currentDateTime = LocalDateTime.now();
LocalTime currentTime = currentDateTime.toLocalTime();
System.out.println("Current date and time: " + currentDateTime);
System.out.println("Extracted time: " + currentTime);

使用场景

  • LocalTime:处理不需要日期信息的时间场景,如计划、日程安排等。
  • LocalDateTime:处理不涉及时区的日期和时间场景,如记录本地事件的发生时间、进行简单的日期时间计算等。

在处理不涉及时区的日期和时间场景时,可以使用LocalTimeLocalDateTime类进行操作。它们提供了丰富的方法来完成日期和时间相关的操作和计算。


十、Duration和Period和ChronoUnit

DurationPeriodChronoUnit都位于java.time包中,用于处理日期和时间间隔的计算。下面分别介绍这三个类的作用:

  1. Duration:表示两个时间点之间的时间段,以秒和纳秒为单位。Duration常用于处理精确到秒或纳秒的时间间隔和计算。它可以处理正负的时间间隔,提供了丰富的方法来完成时间间隔的加减和计算。

例如,计算两个Instant对象之间的间隔:

Instant instant1 = Instant.now();
Thread.sleep(1000); // 等待1秒
Instant instant2 = Instant.now();
Duration duration = Duration.between(instant1, instant2);
System.out.println("Duration: " + duration); // 输出:Duration: PT1S
  1. Period:表示两个日期之间的时间段,以年、月、日为单位。Period常用于处理以年、月、日为单位的日期间隔和计算。它可以处理正负的时间间隔,提供了丰富的方法来完成日期间隔的加减和计算。

例如,计算两个LocalDate对象之间的间隔:

LocalDate date1 = LocalDate.of(2023, Month.JANUARY, 1);
LocalDate date2 = LocalDate.of(2023, Month.APRIL, 21);
Period period = Period.between(date1, date2);
System.out.println("Period: " + period); // 输出:Period: P3M20D
  1. ChronoUnit:是一个枚举类,定义了表示时间单位的常量,如年、月、周、日、小时、分钟、秒等。ChronoUnit可用于计算两个日期或时间点之间的单位间隔,或者表示日期和时间的加减操作的单位。

例如,计算两个LocalDate对象之间的天数差:

LocalDate date1 = LocalDate.of(2023, Month.JANUARY, 1);
LocalDate date2 = LocalDate.of(2023, Month.APRIL, 21);
long daysBetween = ChronoUnit.DAYS.between(date1, date2);
System.out.println("Days between date1 and date2: " + daysBetween); // 输出:Days between date1 and date2: 110

总之,DurationPeriodChronoUnit都是用于处理日期和时间间隔的计算,它们分别针对不同粒度的时间单位提供了丰富的方法和功能。Duration主要用于处理秒和纳秒级别的时间间隔,Period主要用于处理年、月、日级别的日期间隔,而ChronoUnit可用于表示各种时间单位并计算两个日期或时间点之间的单位间隔。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值