Java date and time class summary

Date class

Java in Java The util package provides a Date class that encapsulates the current Date and time.
From jdk1 0 started.
Note that Date cannot be internationalized, and the offset is not uniform. Its month and hour start from 0, the number of days of the month starts from 1, and the year starts from 1900.

A year y is represented by the integer y - 1900.
A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
A date (day of month) is represented by an integer from 1 to 31 in the usual manner.
An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12.

Most of the methods of this class are outdated.

Common methods

The Date class supports two constructors:

  1. The first constructor initializes the current date and time of the object.


  1. The following constructor receives a parameter equal to the number of milliseconds that have elapsed since 00:00:00 on January 1, 1970

Date(long millisec)

The following methods can also be used:

boolean after(Date date)Returns true if the call Date object contains or is later than the specified Date; otherwise, returns false.
boolean before(Date date)Returns true if the call Date object contains or is earlier than the Date specified. Otherwise, returns false.
Object clone( )Call Date object repeatedly.
int compareTo(Date date)The value of the calling object is compared with the date. Returns 0 if the two values are equal. If the calling object is earlier than the date, a negative value is returned. Returns a positive value if the calling object is later than the date.
int compareTo(Object obj)Operate with the same compareTo(Date) if obj is a class date. Otherwise, it throws a ClassCastException.
boolean equals(Object date)If the call Date object contains the same time and Date, the specified Date returns true; otherwise, it returns false.
long getTime( )Returns the number of milliseconds that have elapsed since January 1, 1970.
int hashCode( )Returns the hash code of the calling object.
void setTime(long time)Sets the specified time, which represents the elapsed time in milliseconds from the time and date of midnight on January 1, 1970.
String toString( )Call the Date object to convert it into a string and return the result.

Calendar Class

From jdk1 1 at first. It is used to represent the Calendar. It refers to the Gregorian Calendar, which is the most common Gregorian Calendar. It is an abstract class. It is the template of all Calendar classes. Therefore, the constructor cannot be used to create the Calendar object, but it provides several static methods to obtain the Calendar object. According to the TimeZone, the locale class obtains the specific Calendar. If it is not specified, the default TimeZone will be used, Locale to create a Calendar.

// Create a default Calendar object
Calendar calendar = Calendar.getInstance()

// Take the Date object from the Calendar object
Date date = calendar.getTime()

// Get the corresponding Calendar object through the Date object
// Calendar does not directly receive the constructor of the Date object, so it can only be used in the following way
Calendar calendar1 = Calendar.getInstance();

Note the following time fields:
Calendar.MONTH stands for month. The start of month is 0, and 0 stands for January.
Calendar.HOUR 12 hour system
Calendar.HOUR_OF_DAY 24 hours

Common methods

add(int field, int amount)Adds (positive) or subtracts (negative) the specified amount of time to the specified calendar field according to calendar rules
roll(int field, int amount)Similar to the add method, the difference is that when the amount exceeds the maximum range that the field can represent, it will not carry forward to the previous field.
get(int field)Returns the value of the specified calendar field
getActualMaximum(int field)Gets the maximum value that the specified calendar field may have
getActualMinimum(int field)Gets the minimum value that the specified calendar field may have
set(int field, int value)Sets the given calendar field to the given value
set(int year, int month, int date)Set year, month and day of Calendar object
set(int year, int month, int date, int hourOfDay, int minute, int second)Set the year, month, day, hour, minute and second of the Calendar object

Important points to note

Differences between add and roll methods:

add(int field, int amount) method
Adds (positive) or subtracts (negative) the specified amount of time to the specified calendar field according to calendar rules

  1. When the modified field exceeds its allowable range, carry will occur, that is, the upper level field will also change
  2. If the field of the next level also needs to be changed, the changed field will also be corrected to the value with the smallest change.
Calendar calendar = Calendar.getInstance();
calendar.set(2021, 0, 31);
// 2021-1-31

calendar.add(Calendar.MONTH, 1);
// 2021-02-28

calendar.add(Calendar.MONTH, 15);
// 2022-05-28

roll(int field, int amount)

  1. Similar to the add method. The difference is that when the amount exceeds the maximum range that the field can represent, it will not carry forward to the previous field.
  2. The processing rules of the next level field are similar to the add method
Calendar calendar = Calendar.getInstance();
calendar.set(2021, 0, 31);
calendar.roll(Calendar.MONTH, 15);
// 2021-05-28

Set the fault tolerance of Calendar

When calling the set() method to change the value of the specified time field, an illegal parameter may be passed in, for example, the MONTH exceeds 11.

By calling setLenient(boolean lenient) method:
It is used to set fault tolerance. Calendar supports better fault tolerance by default. Turn off fault tolerance by setLenient(false) and let it perform strict parameter checking. When the value range allowed by the specified time field is exceeded, the program will throw an exception.

The set() method delays modification

set(int field, int value)
Although the field field is modified immediately, the time represented by the calendar will not be modified immediately. The calendar time will not be recalculated until get(), getTime(), getTimeInMillis(), add(), and roll() are called. This is called delayed modification of the set() method.
Advantage: multiple calls to the set() method will not trigger multiple unnecessary calculations (calculating a long integer representing the actual time).

New date and time package in Java 8

Java 8 adds a new Java Time package.
It also adds a Java time. The temporary package includes interfaces such as temporary and TemporalAdjuster. The following classes implement these interfaces. Please pay attention to them when using.


Gets the current date and time of the specified time zone.
This class can replace the currentTimeMillis() method of the System class, and provides more methods to obtain the date and time.


Represents the duration. It can be easily obtained for a period of time.


Represents a specific moment, which can be accurate to nanoseconds.


Represents a date without a time zone.

LocalDate today =;
// Get Monday and Sunday of the week
LocalDate monday = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
LocalDate sunday = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));


Represents a time without a time zone.


Represents a date and time without time zone.


Represents month day.


Represents the year.


Represents month and year.


Represents a date and time with time zone


Represents a time zone


Enumeration class, which defines the enumeration from Sunday to Saturday.


Enumeration class, which defines the enumeration from January to December.

Relevant cases are as follows:

public static void main(String[] args) {

        Clock clock = Clock.systemUTC();
        System.out.println("Current time:" + clock.instant());
        // Get the number of milliseconds corresponding to clock, and system The output of currenttimemillis() is the same

        Duration duration = Duration.ofSeconds(60100);

        Instant instant =;

        LocalDate localDate =;

        // Set to a day
        System.out.println(LocalDate.of(2021, 1, 1));

        LocalTime localTime =;

        Year year =;

        YearMonth yearMonth =;

        MonthDay monthDay =;


Conversion of LocalDateTime, LocalDate and Date

LocalDateTime to LocalDate

Call the toLocalDate() method directly

LocalDateTime localDateTime =;
LocalDate localDate = localDateTime.toLocalDate();

LocalDateTime to Date

When converting LocalDateTime to Date, you need to use several classes of Java 8

ZoneId/ZoneOffset: indicates the time zone
ZonedDateTime: represents the date and time of a specific time zone
Instant: represents the time, which does not directly correspond to the year, month and day information. It needs to be converted through the time zone

LocalDateTime localDateTime =;
//Get the system default time zone
ZoneId zoneId = ZoneId.systemDefault();
//Date and time in time zone
ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
//Get time
Date date = Date.from(zonedDateTime.toInstant());
System.out.println("Before formatting: localDateTime:" + localDateTime + "  Date:" + date);
//Format LocalDateTime, Date
DateTimeFormatter localDateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("After formatting: localDateTime:" + localDateTimeFormat.format(localDateTime) + "  Date:" + dateFormat.format(date));

The output results are as follows:

Before formatting: localDateTime:2022-01-03T17:43:54.544  Date:Mon Jan 03 17:43:54 CST 2022
 After formatting: localDateTime:2022-01-03 17:43:54  Date:2022-01-03 17:43:54

LocalDate to LocalDateTime

Generally, the atTime() method is called for assignment

LocalDate localDate =;
LocalDateTime localDateTime1 = localDate.atStartOfDay();
LocalDateTime localDateTime2 = localDate.atTime(8,20,33);
LocalDateTime localDateTime3 = localDate.atTime(;

LocalDate to Date

First call the atStartOfDay() method to convert LocalDateTime and then Date

LocalDate localDate =;
ZoneId zoneId = ZoneId.systemDefault();
Date date = Date.from(localDate.atStartOfDay().atZone(zoneId).toInstant());

Date to LocalDateTime

Turn ZonedDateTime first and then LocalDateTime

Date date = new Date();
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = date.toInstant().atZone(zoneId).toLocalDateTime();

Date to LocalDate

Same as LocalDate

Date date = new Date();
ZoneId zoneId = ZoneId.systemDefault();
LocalDate localDate = date.toInstant().atZone(zoneId).toLocalDate();

Keywords: Java Back-end

Added by Nabster on Mon, 03 Jan 2022 20:23:16 +0200