Java Basics--Date Time Class

Table of contents

foreword

Instant (timestamp) class

LocalData(date) class

LocalTime (time) class

LocalDataTime (date time) class

Duration (time interval) class

Period (date interval) class

Clock (get time zone) class


foreword

In development, it is often necessary to deal with date and time. Java provides a set of APIs dedicated to dealing with date and time. The date and time classes include LocalDate, LocalTime, Instant, Duration, and Period. These classes are all Included in the java.time package.

class name

Functional description

Instant

Represents the moment, representing the timestamp

LocalDate

A date without a specific time

LocalTime

time without date

LocalDateTime

Contains date and time

Duration

A time-based value measures an amount of time

Period

Calculate the date time difference, only accurate to the year, month, and day

Clock

A clock system for finding the current time

Instant ( timestamp ) class

The Instant class represents a certain time. Its interior is composed of two Long fields,

  • The first part is to save the number of seconds from the standard Java computing era (that is, starting from January 1, 1970) to the current time, that is, the timestamp (Timestamp). The timestamp represents the number of seconds that have elapsed since the reference time point.

  • The second part is to save the number of nanoseconds. A nanosecond is a finer unit of time, representing one billionth of a second.

common method

  • now(): Get the current instant using the system clock.
  • now(Clock clock): Get the current instant using the specified clock.
  • ofEpochSecond(long epochSecond)Instant: Gets an instance using the number of seconds since the standard Java compute epoch .
  • ofEpochMilli(long epochMilli)Instant: Gets an instance using the number of milliseconds since the standard Java compute epoch .
  • getEpochSecond(): Get the seconds part of the timestamp.
  • getNano(): Get the nanosecond part of the timestamp.
  • parse(CharSequence text): Convert the string representing the time to the corresponding Instantobject.
  • from(TemporalAccessor tenporal): Get an Instantinstance of a time object.
  • plusSeconds(long seconds) AND  plusMillis(long millis): Adds the specified number of seconds or milliseconds to the timestamp.
  • minusSeconds() And  minusMillis(): Subtract the specified number of seconds or milliseconds from the timestamp.
  • isBefore() And  isAfter() method: compare the sequence of two timestamps.

Sample code:

import java.time.Clock;
import java.time.Instant;

public class InstantExample {
    public static void main(String[] args) {
        // 获取当前时间的瞬时实例
        Instant now = Instant.now();
        System.out.println("当前时间:" + now);

        // 使用指定时钟获取当前时间的瞬时实例
        Clock clock = Clock.systemUTC();
        Instant nowWithClock = Instant.now(clock);
        System.out.println("当前时间(使用指定时钟):" + nowWithClock);

        // 使用从自标准Java计算时代开始的秒数创建Instant实例        
        Instant epochSecondInstant = Instant.ofEpochSecond(1234567890);
        System.out.println("自1970年1月1日起的秒数对应的时间:" + epochSecondInstant);

        // 使用从自标准Java计算时代开始的毫秒数创建Instant实例
        Instant epochMilliInstant = Instant.ofEpochMilli(1627368000000L);
        System.out.println("自1970年1月1日起的毫秒数对应的时间:" + epochMilliInstant);

        // 获取时间戳的秒数部分
        long seconds = now.getEpochSecond();
        System.out.println("时间戳的秒数部分:" + seconds);

        // 获取时间戳的纳秒数部分
        int nanos = now.getNano();
        System.out.println("时间戳的纳秒数部分:" + nanos);

        // 将表示时间的字符串转换为Instant对象
        String timeString = "2023-08-14T10:30:00Z";
        Instant parsedInstant = Instant.parse(timeString);
        System.out.println("解析后的时间:" + parsedInstant);

        // 在时间戳的基础上增加指定的秒数或毫秒数
        Instant plusSecondsInstant = now.plusSeconds(3600);
        Instant plusMillisInstant = now.plusMillis(1000);
        System.out.println("增加1小时后的时间:" + plusSecondsInstant);
        System.out.println("增加1秒后的时间:" + plusMillisInstant);

        // 在时间戳的基础上减去指定的秒数或毫秒数
        Instant minusSecondsInstant = now.minusSeconds(1800);
        Instant minusMillisInstant = now.minusMillis(500);
        System.out.println("减去30分钟后的时间:" + minusSecondsInstant);
        System.out.println("减去0.5秒后的时间:" + minusMillisInstant);

        // 比较两个时间戳的先后顺序
        Instant earlierInstant = Instant.parse("2023-08-14T09:00:00Z");
        Instant laterInstant = Instant.parse("2023-08-14T11:00:00Z");
        boolean isBefore = earlierInstant.isBefore(laterInstant);
        boolean isAfter = earlierInstant.isAfter(laterInstant);
        System.out.println("earlierInstant是否在laterInstant之前:" + isBefore);
        System.out.println("earlierInstant是否在laterInstant之后:" + isAfter);
    }
}

operation result:

当前时间:2023-08-14T09:41:00.027378100Z
当前时间(使用指定时钟):2023-08-14T09:41:00.037343Z
自1970年1月1日起的秒数对应的时间:2009-02-13T23:31:30Z
自1970年1月1日起的毫秒数对应的时间:2021-07-27T06:40:00Z
时间戳的秒数部分:1692006060
时间戳的纳秒数部分:27378100
解析后的时间:2023-08-14T10:30:00Z
增加1小时后的时间:2023-08-14T10:41:00.027378100Z
增加1秒后的时间:2023-08-14T09:41:01.027378100Z
减去30分钟后的时间:2023-08-14T09:11:00.027378100Z
减去0.5秒后的时间:2023-08-14T09:40:59.527378100Z
earlierInstant是否在laterInstant之前:true
earlierInstant是否在laterInstant之后:false

LocalData( date ) class

The LocalData class is a date class introduced by Java 8, which is used to represent date (year, month, day) information. This class has the following methods:

  1. now(): This is a static method that returns an object representing the current date LocalDate. For example, LocalDate.now()an object representing today's date will be returned.
  2. of(int year, int month, int dayOfMonth): This is another static method that creates LocalDatean object by specifying the year, month, and day. The parameter yearrepresents the year, monthrepresents the month (between 1 and 12), dayOfMonthrepresents a certain day in the month.
  3. format(DateTimeFormatter formatter): This method converts LocalDatethe object into a string representation according to the specified format. An DateTimeFormatterobject needs to be passed in, which can use a predefined format or a custom format. For example, date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))a date string with the format "year-month-day" will be returned.
  4. plusYears(long years)/ : These methods are used to increase or decrease the specified number of years on an minusYears(long years)existing object. LocalDateThe parameter yearsindicates the number of years to add or subtract.
  5. plusMonths(long months)/ : Similar to the methods above, these methods are used to increment or decrement the specified number of months on an minusMonths(long months)existing object.LocalDate
  6. plusDays(long days)/ : These methods are used to increment or decrement the specified number of days on an minusDays(long days)existing object.LocalDate
  7. isBefore(LocalDate other)/ isAfter(LocalDate other): These two methods are used to compare LocalDatethe sequence of two objects. isBefore()The method returns a Boolean value indicating whether the date is before the parameter date; isAfter()the method returns a Boolean value indicating whether the date is after the parameter date.
  8. getYear()// getMonthValue(): getDayOfMonth()These methods are used to obtain LocalDatethe year, month, and day information of the object.
  9. isLeapYear():Used to determine whether the specified year is a leap year.

Sample code:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class myclass {
    public static void main(String[] args) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        System.out.println("当前日期:" + currentDate);

        // 创建指定日期
        LocalDate customDate = LocalDate.of(2023, 8, 14);
        System.out.println("自定义日期:" + customDate);

        // 格式化日期为字符串
        String formattedDate = customDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        System.out.println("格式化后的日期:" + formattedDate);

        // 增减年份
        LocalDate futureDate = customDate.plusYears(2);
        System.out.println("增加两年后的日期:" + futureDate);

        // 判断日期先后
        boolean isBefore = customDate.isBefore(currentDate);
        boolean isAfter = customDate.isAfter(currentDate);
        System.out.println("自定义日期是否在当前日期之前:" + isBefore);
        System.out.println("自定义日期是否在当前日期之后:" + isAfter);

        // 获取年、月、日
        int year = customDate.getYear();
        int month = customDate.getMonthValue();
        int dayOfMonth = customDate.getDayOfMonth();
        System.out.println("年:" + year);
        System.out.println("月:" + month);
        System.out.println("日:" + dayOfMonth);

        // 判断闰年
        boolean isLeapYear = customDate.isLeapYear();
        System.out.println("自定义日期所在年份是否为闰年:" + isLeapYear);
    }
}

operation result:

当前日期:2023-08-14
自定义日期:2023-08-14
格式化后的日期:2023-08-14
增加两年后的日期:2025-08-14
自定义日期是否在当前日期之前:false
自定义日期是否在当前日期之后:false
年:2023
月:8
日:14
自定义日期所在年份是否为闰年:false

LocalTime ( time) class

The LocalTime class is used to represent time, usually hours, minutes and seconds. Like the LocalData class, this class cannot represent instant information on the timeline, but only a description of time. The method of obtaining the time object is provided in the LocalTime class, which is similar to the usage of LocalData.

At the same time, the LocalTime class also provides common methods such as time formatting, adding and subtracting hours, minutes, and seconds corresponding to the date class. These methods correspond to the LocalData ( date ) class, and we will not list them in detail here.

Sample code:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

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

        // 创建指定时间
        LocalTime customTime = LocalTime.of(12, 30, 45);
        System.out.println("自定义时间:" + customTime);

        // 格式化时间为字符串
        String formattedTime = customTime.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
        System.out.println("格式化后的时间:" + formattedTime);

        // 增减小时数
        LocalTime futureTime = customTime.plusHours(2);
        System.out.println("增加两小时后的时间:" + futureTime);

        // 判断时间先后
        boolean isBefore = customTime.isBefore(currentTime);
        boolean isAfter = customTime.isAfter(currentTime);
        System.out.println("自定义时间是否在当前时间之前:" + isBefore);
        System.out.println("自定义时间是否在当前时间之后:" + isAfter);

        // 获取小时、分钟、秒
        int hour = customTime.getHour();
        int minute = customTime.getMinute();
        int second = customTime.getSecond();
        System.out.println("小时:" + hour);
        System.out.println("分钟:" + minute);
        System.out.println("秒:" + second);
    }
}

operation result:

当前时间:18:04:40.272290700
自定义时间:12:30:45
格式化后的时间:12:30:45
增加两小时后的时间:14:30:45
自定义时间是否在当前时间之前:true
自定义时间是否在当前时间之后:false
小时:12
分钟:30
秒:45

LocalDataTime ( date time ) class

The LocalDataTime class is a combination of the date (LocalDate) class and the time (LocalTime) class. It includes both the date and the time. By viewing the API, we can know that the methods in the LocalDataTime class include the methods of the LocalData class and the LocalTime class.

It should be noted that the default format of LocalDateTime is 2020-02-29T21:23:26.774, which may not match the format we often use, so it is often used with DateTimeFormatter to specify the format, except for methods in the LocalData and LocalTime classes , additionally provides a conversion method.

The following are some commonly used methods of the LocalDateTime class:

  1. now(): static method, returns the LocalDateTime object of the current date and time.
  2. of(int year, int month, int dayOfMonth, int hour, int minute) / of(int year, int month, int dayOfMonth, int hour, int minute, int second): static method, by specifying year, month, day, Hours, minutes, and seconds (optional) to create a LocalDateTime object.
  3. parse(CharSequence text): static method that parses a string into a LocalDateTime object.
  4. format(DateTimeFormatter formatter): Convert the LocalDateTime object to a string representation according to the specified format.
  5. toLocalDate(): Get the date part of the LocalDateTime object and return the LocalDate object.
  6. toLocalTime(): Get the time part of the LocalDateTime object and return the LocalTime object.
  7. plusYears(long years) / minusYears(long years): Adds or subtracts the specified number of years to an existing LocalDateTime object.
  8. plusMonths(long months) / minusMonths(long months): Adds or subtracts the specified number of months to an existing LocalDateTime object.
  9. plusDays(long days) / minusDays(long days): Adds or subtracts the specified number of days to an existing LocalDateTime object.
  10. plusHours(long hours) / minusHours(long hours): Add or subtract the specified number of hours on an existing LocalDateTime object.
  11. plusMinutes(long minutes) / minusMinutes(long minutes): Adds or subtracts the specified number of minutes on an existing LocalDateTime object.
  12. plusSeconds(long seconds) / minusSeconds(long seconds): Adds or subtracts the specified number of seconds on an existing LocalDateTime object.
  13. getYear() / getMonthValue() / getDayOfMonth(): Get the year, month, and day information of the LocalDateTime object.

Sample code: 

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

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

        // 创建指定的日期和时间
        LocalDateTime customDateTime = LocalDateTime.of(2023, 8, 14, 12, 30);
        System.out.println("自定义日期和时间:" + customDateTime);

        // 格式化日期时间为字符串
        String formattedDateTime = customDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println("格式化后的日期和时间:" + formattedDateTime);

        // 增减年数、月数、天数、小时数、分钟数、秒数
        LocalDateTime futureDateTime = customDateTime.plusYears(1).minusMonths(2).plusDays(15).minusHours(3).plusMinutes(10).plusSeconds(30);
        System.out.println("操作后的日期和时间:" + futureDateTime);

        // 获取日期和时间部分
        LocalDate datePart = customDateTime.toLocalDate();
        LocalTime timePart = customDateTime.toLocalTime();
        System.out.println("日期部分:" + datePart);
        System.out.println("时间部分:" + timePart);

        // 获取年、月、日信息
        int year = customDateTime.getYear();
        int month = customDateTime.getMonthValue();
        int dayOfMonth = customDateTime.getDayOfMonth();
        System.out.println("年:" + year);
        System.out.println("月:" + month);
        System.out.println("日:" + dayOfMonth);
    }
}

operation result:

当前日期和时间:2023-08-14T18:09:24.472147600
自定义日期和时间:2023-08-14T12:30
格式化后的日期和时间:2023-08-14 12:30:00
操作后的日期和时间:2024-06-29T09:40:30
日期部分:2023-08-14
时间部分:12:30
年:2023
月:8
日:14

Duration (time interval) class

The Duration class is a class introduced in Java 8 to represent time intervals. It can be used to calculate the difference between two points in time, and to convert between different units such as seconds, minutes, hours, etc.

The following are some commonly used methods of the Duration class:

  1. ofDays(long days) / ofHours(long hours) / ofMinutes(long minutes): A static method that creates a duration representing the specified number of days, hours or minutes.
  2. ofSeconds(long seconds) / ofMillis(long milliseconds) / ofNanos(long nanos): static method that creates a duration representing the specified number of seconds, milliseconds or nanoseconds.
  3. between(Temporal startInclusive, Temporal endExclusive): A static method that creates a duration representing the difference between the start time and the end time.
  4. plus(Duration duration) / minus(Duration duration): Add or subtract the duration of another Duration object on the existing Duration object.
  5. toDays() / toHours() / toMinutes(): Convert the duration to the corresponding number of days, hours or minutes.
  6. toSeconds() / toMillis() / toNanos(): Convert the duration to the corresponding number of seconds, milliseconds or nanoseconds.
  7. getSeconds() / getNano(): Get the number of seconds and nanoseconds in the duration.
  8. isNegative() / isZero(): Determine whether the duration is negative or zero.

Sample code:  

import java.time.Duration;

public class myclass {
    public static void main(String[] args) {
        // 创建一个持续时间,表示5小时30分钟15秒
        Duration duration1 = Duration.ofHours(5).plusMinutes(30).plusSeconds(15);
        System.out.println("Duration 1: " + duration1); // 输出:PT5H30M15S

        // 创建一个持续时间,表示1分钟
        Duration duration2 = Duration.ofMinutes(1);
        System.out.println("Duration 2: " + duration2); // 输出:PT1M

        // 计算两个持续时间之间的差异
        Duration difference = duration1.minus(duration2);
        System.out.println("Difference: " + difference); // 输出:PT5H29M15S

        // 获取持续时间的小时数、分钟数和秒数
        long hours = difference.toHours();
        long minutes = difference.toMinutesPart();
        long seconds = difference.toSecondsPart();
        System.out.println("Hours: " + hours); // 输出:5
        System.out.println("Minutes: " + minutes); // 输出:29
        System.out.println("Seconds: " + seconds); // 输出:15

        // 判断持续时间是否为负值或零值
        boolean isNegative = difference.isNegative();
        boolean isZero = difference.isZero();
        System.out.println("是负的? " + isNegative); // 输出:false
        System.out.println("是零吗? " + isZero); // 输出:false
    }
}

Period (date interval) class

 Period is mainly used to calculate the interval between two dates. It is the same as Duration. It also calculates the date interval through between, and provides three common methods for obtaining the year, month and day, namely getYears(), getMonths() and getDays().

Sample code:  

import java.time.LocalDate;
import java.time.Period;

public class myclass {
    public static void main(String[] args) {
        // 创建两个日期
        LocalDate startDate = LocalDate.of(2023, 1, 1);
        LocalDate endDate = LocalDate.of(2023, 4, 30);

        // 计算日期之间的差异
        Period period = Period.between(startDate, endDate);
        System.out.println("日期间隔: " + period); // 输出:P3M29D

        // 获取年、月、日的差异
        int years = period.getYears();
        int months = period.getMonths();
        int days = period.getDays();
        System.out.println("年: " + years); // 输出:0
        System.out.println("月: " + months); // 输出:3
        System.out.println("日: " + days); // 输出:29

        // 添加日期间隔到指定日期
        LocalDate newDate = startDate.plus(period);
        System.out.println("新日期: " + newDate); // 输出:2023-04-30

        // 判断日期间隔是否为负值或零值
        boolean isNegative = period.isNegative();
        boolean isZero = period.isZero();
        System.out.println("是否为负值? " + isNegative); // 输出:false
        System.out.println("是否为零值? " + isZero); // 输出:false
    }
}

Clock (get time zone) class

Clockclass is an abstract class in Java used to obtain current time, date and time zone information. It provides a generic way to access the system clock and get the current time in different timezones.

  1. systemDefaultZone(): static method, returns the system clock using the system default time zone.
  2. systemUTC(): A static method that returns the system clock using Coordinated Universal Time (UTC).
  3. tick(Clock fixedClock, Duration tickDuration): A static method that returns a "tick" clock that wraps the specified clock, advancing the specified duration each time.
  4. fixed(Instant fixedInstant, ZoneId zone): static method, returns a fixed clock, always returns the specified instant and time zone.
  5. offset(Clock baseClock, Duration offsetDuration): A static method that returns a clock that is offset by the specified duration relative to the base clock.
  6. millis(): An instance method that returns the number of milliseconds since midnight, January 1, 1970.
  7. instant(): instance method, returns the current instant of the current clock.
  8. getZone(): instance method, returns the time zone information of the clock.

Sample code:   

import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;

public class myclass {
    public static void main(String[] args) {
        // 获取系统默认时区的时钟
        Clock systemDefaultClock = Clock.systemDefaultZone();
        System.out.println("系统默认时钟:" + systemDefaultClock);

        // 获取使用协调世界时(UTC)的系统时钟
        Clock systemUTCClock = Clock.systemUTC();
        System.out.println("系统UTC时钟:" + systemUTCClock);

        // 创建一个滴答时钟,每次前进1秒钟
        Clock tickClock = Clock.tick(systemDefaultClock, Duration.ofSeconds(1));
        System.out.println("滴答时钟:" + tickClock);

        // 创建一个固定的时钟,始终返回指定的瞬间和时区
        Instant fixedInstant = Instant.parse("2022-01-01T00:00:00Z");
        ZoneId fixedZone = ZoneId.of("Asia/Shanghai");//亚洲/上海
        Clock fixedClock = Clock.fixed(fixedInstant, fixedZone);
        System.out.println("固定时钟:" + fixedClock);

        // 创建一个相对于基准时钟偏移10秒钟的时钟
        Clock baseClock = Clock.systemDefaultZone();
        Duration offsetDuration = Duration.ofSeconds(10);
        Clock offsetClock = Clock.offset(baseClock, offsetDuration);
        System.out.println("偏移时钟:" + offsetClock);

        // 获取当前时钟的毫秒数
        long millis = systemDefaultClock.millis();
        System.out.println("毫秒数:" + millis);

        // 获取当前时钟的当前瞬间
        Instant instant = systemDefaultClock.instant();
        System.out.println("当前瞬间:" + instant);

        // 获取当前时钟的时区信息
        ZoneId zone = systemDefaultClock.getZone();
        System.out.println("时区:" + zone);
    }
}

Guess you like

Origin blog.csdn.net/m0_74293254/article/details/132275909