Detailed explanation of Java Date object

1. The Java Date object

The Java Date class represents a date and time and can store the number of milliseconds accumulated since 00:00 on January 1, 1970 (Greenwich Mean Time). Date objects support date calculation and display, and can exchange time data with other systems.

  1. Create a Date object

There are many ways to create a Date object in Java, for example:

(1) Create an object of the current date and time using an empty constructor.

Date date = new Date();

(2) Create an object at a specified time using a constructor with a specified number of milliseconds.

Date date = new Date(1618977192000L);
  1. common method

The Date class provides the following common methods:

(1) getTime(): Returns the number of milliseconds accumulated since January 1, 1970 at 00:00.

(2) setTime(long time): Set the number of milliseconds accumulated since 0:00 on January 1, 1970.

(3) equals(Object obj): Compares whether the current date and time are equal to another date and time.

(4) compareTo(Date anotherDate): Compare the current date and time with another date and time, return a negative number if the current date and time is earlier, return 0 if they are equal, and return a positive number if the current date and time is later .

(5) before(Date when) and after(Date when): indicate whether the current date and time are before or after another date and time respectively.

  1. question

The Date class suffers from the following problems:

(1) Mutability issues: Date objects are mutable, so concurrency issues may occur in a multi-threaded environment.

(2) Confusion problem: The getYear() method provided by the Date class returns the year starting from 1900, and the month starts from 0.

(3) Does not support internationalization: The Date class does not support internationalization, so dates and times cannot be output according to different languages ​​and cultures.

2. Time formatting

Java provides the SimpleDateFormat class to format and parse dates and times. The SimpleDateFormat class uses predefined patterns to specify date and time formats, and can also output or parse dates and times through custom patterns.

  1. common mode

Here are some commonly used predefined patterns:

model describe
yyyy-MM-dd date (year-month-day)
HH:mm:ss time (hour:minute:second)
yyyy-MM-dd HH:mm:ss date time (year-month-day hour:minute:second)
E Day of the week
MMM Month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)
yyy/MM/dd HH:mm:ss ZZ custom datetime format
  1. Format date and time using SimpleDateFormat

Use SimpleDateFormat to convert dates and times of type Date to strings of the specified pattern.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String strDate = sdf.format(date);
System.out.println("当前日期时间为:" + strDate);
  1. Parse dates and times using SimpleDateFormat

Use SimpleDateFormat to convert the string of the specified pattern into date and time of Date type, and also output date and time according to different languages ​​and cultures.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = "2022-08-10 12:34:56";
try {
    
    
    Date date = sdf.parse(strDate);
    System.out.println("解析后的日期时间为:" + date);
} catch (ParseException e) {
    
    
    e.printStackTrace();
}
  1. question

The SimpleDateFormat class has the following problems:

(1) Thread safety issues: SimpleDateFormat objects are mutable, so concurrency issues may occur in a multi-threaded environment.

(2) Confusion problem: The uppercase and lowercase letter forms provided by the SimpleDateFormat class may cause the pattern to be ambiguous.

(3) Does not support internationalization issues: The SimpleDateFormat class does not support internationalization, so dates and times cannot be output according to different languages ​​and cultures.

3. Java 8 time and date API

Java 8 introduces a new time and date API (Java Time API), which provides classes and methods that are easier to understand and use, and overcomes many problems with the Date class and the SimpleDateFormat class. The new time and date API is immutable, supports thread safety and internationalization, and provides more flexible and powerful date and time processing capabilities.

  1. LocalDate

The LocalDate class represents a date without time and time zone information. The current date can be obtained using the now() method, and operations such as adding and subtracting days, months, and years are supported.

LocalDate date = LocalDate.now();
System.out.println("当前日期为:" + date);
  1. LocalTime

The LocalTime class represents time without date and time zone information. You can use the now() method to get the current time, and it supports operations such as adding and subtracting hours, minutes and seconds.

LocalTime time = LocalTime.now();
System.out.println("当前时间为:" + time);
  1. LocalDateTime

The LocalDateTime class represents a date and time without time zone information. You can use the now() method to get the current date and time, and support operations such as adding and subtracting days, months, and years.

LocalDateTime dateTime = LocalDateTime.now();
System.out.println("当前日期时间为:" + dateTime);
  1. ZonedDateTime

The ZonedDateTime class represents date, time, and time zone information. You can use the now() method to get the current date, time and time zone, and support operations such as adding and subtracting days, months and years.

ZonedDateTime zonedDateTime = ZonedDateTime.now();
System.out.println("当前日期时间和时区为:" + zonedDateTime);
  1. Instant

The Instant class represents a Unix timestamp, the number of seconds and nanoseconds since midnight, January 1, 1970. The current Unix timestamp can be obtained using the now() method, and operations such as adding and subtracting seconds and nanoseconds are supported.

Instant instant = Instant.now();
System.out.println("当前 Unix 时间戳为:" + instant);
  1. DateTimeFormatter

The DateTimeFormatter class provides methods for formatting and parsing dates and times, and supports custom modes and supports internationalization.

LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String strDateTime = dateTime.format(formatter);
System.out.println("当前日期时间为:" + strDateTime);
  1. question

The Java 8 time and date API does not have the problems of the Date class and the SimpleDateFormat class, provides classes and methods that are easier to understand and use, and overcomes problems such as thread safety, confusion, and lack of support for internationalization.

4. Summary

This article introduced the Java Date object and time formatting. The Java Date class represents date and time, and can store the number of milliseconds accumulated since 0:00 on January 1, 1970. Concurrency problems may occur in a multi-threaded environment, and it is confusing and does not support internationalization. Java provides the SimpleDateFormat class to format and parse dates and times, and there are issues such as thread safety, confusion, and no support for internationalization. Java 8 introduces a new time and date API (Java Time API), which provides classes and methods that are easier to understand and use, and overcomes many existing problems. Common patterns are discussed, as well as code examples using various classes and methods. I hope readers can understand these knowledge points and better apply them to deal with date and time related issues.

Guess you like

Origin blog.csdn.net/u012581020/article/details/130706805