Detailed explanation of date and time classes in Java

Table of contents


Preface

Recently, during my internship, I encountered many needs related to date and time, such as adding and subtracting time and converting time formats to each other. Java used Date to calculate time in the early days. Later, most of the methods of the Date class became obsolete, and it turned to the Calendar class to replace the Date class. However, the Calendar class was also unsatisfactory. Therefore, this article specifically summarizes and summarizes the basic concepts, common operations and related classes of the Date class in Java to facilitate future development. I hope it will be helpful to everyone.


1. Date class

1.  Basic concepts

The java.util package provides the Date class to encapsulate the current date and time. The Date class provides two constructors to instantiate Date objects.

The first constructor initializes the object with the current date and time.

Date( )

The second constructor receives a parameter, which is the number of milliseconds since January 1, 1970.

Date(long millisec)

		Date date2= new Date();
        System.out.println(date2);


        //参数表示1970-01-01 00:00:00到指定时间的毫秒数
        Date date1 = new Date(14686531L);
        System.out.println(date1);

2. Common methods

2.1 Date comparison

Java uses the following three methods to compare two dates:

  1. Use the getTime() method to get two dates ( number of milliseconds since January 1, 1970 ) and then compare the two values.
  2. Use the methods before(), after() and equals(). For example, if the 12th of a month is earlier than the 18th, then new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.
  3. Use the compareTo() method, which is defined by the Comparable interface, which the Date class implements.

2.2 Use SimpleDateFormat to format dates

Because it is very difficult to convert between Date class and string time, you can consider indirect conversion through other subclasses of Date class. DateFormat is an abstract class for date/time formatting subclasses that is concerned with formatting and parsing dates or times in a language-independent manner. Therefore, use its subclass SimpleDateFormat to convert dates and strings to each other.

public static void main(String[] args) throws Exception {

        // 定义输出格式   
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 将字符串转化为日期   
        Date date = sdf.parse("2023-11-11 11:11:11");
        System.out.println(date);

        Date date = new Date();
        // 将日期转化为字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String str = sdf.format(date);
        System.out.println(str);
    }

2. DateFormat class

1. Basic concepts

java.text.DateFormat is an abstract class of the date/time formatting subclass. We use this class to help us complete the conversion between date and text, that is, we can convert back and forth between Date objects and String objects.

  • Formatting : Convert from Date object to String object according to the specified format. (format)
  • Parsing : Convert from String object to Date object according to the specified format. (parse)

2. Common methods

2.1 Construction method

Since DateFormat is an abstract class and cannot be used directly, a commonly used subclass is required java.text.SimpleDateFormat. This class requires a schema (format) to specify the formatting or parsing criteria. The construction method is:

public SimpleDateFormat(String pattern): Constructs a SimpleDateFormat with the given pattern and date format symbols of the default locale.

The parameter pattern is a string representing a custom format for date and time.

Format rules

Commonly used format rules are:

Identifier letter (case sensitive) meaning
y Year
M moon
d Day
H hour
m point
s Second

The code to create a SimpleDateFormat object is as follows:

import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class Demo02SimpleDateFormat {
    public static void main(String[] args) {
        // 对应的日期格式如:2023-11-11 11:11:11
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }    
}

2.2 Common methods of DateFormat class

Commonly used methods of the DateFormat class are:

1. public String format(Date date): Format the Date object into a string.

The code of the format method is as follows:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
 把Date对象转换成String
*/
public class Demo03DateFormatMethod {
    public static void main(String[] args) {
        Date date = new Date();
        // 创建日期格式化对象,在获取格式化对象时可以指定风格
        DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        String str = df.format(date);
        System.out.println(str); // 2020年09月19日
    }
}

2. public Date parse(String source): Parse the string into a Date object.

The code of the parse method is as follows:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
 把String转换成Date对象
*/
public class Demo04DateFormatMethod {
    public static void main(String[] args) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        String str = "2023年11月11日";
        Date date = df.parse(str);
        System.out.println(date); // Tue Dec 11 00:00:00 CST 2023
    }
}

3. Calendar class

1. Basic concepts

We can now format and create a date object, but how can we set and get specific parts of the date data, such as the hour, day, or minute? And how can we add or subtract values ​​from these parts of the date? What? The answer is to use the Calendar class.

The Calendar class is much more powerful than the Date class, and its implementation is also more complex than the Date class.

The Calendar class is an abstract class that implements objects of specific subclasses in actual use. The process of creating objects is transparent to programmers, and only needs to be created using the getInstance method.

java.util.CalendarIt is a calendar class that appears after Date and replaces many Date methods. This class encapsulates all possible time information as static member variables for easy access. The calendar class is convenient for obtaining various time attributes.

2. Commonly used methods

2.1 Construction method

Calendar is an abstract class. Due to language sensitivity, the Calendar class is not created directly when creating an object, but is created through a static method and returns a subclass object, as follows:

Calendar static method

  • public static Calendar getInstance(): Gets a calendar using the default time zone and locale

For example:

import java.util.Calendar;

public class Demo06CalendarInit {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
    }    
}

2.2 Common methods

According to the API documentation of the Calendar class, common methods are:

  • public int get(int field): Returns the value of the given calendar field.
  • public void set(int field, int value): Sets the given calendar field to the given value.
  • public abstract void add(int field, int amount): Add or subtract the specified amount of time to a given calendar field according to the rules of the calendar.
  • public Date getTime(): Returns a Date object representing this Calendar time value (the millisecond offset from the epoch to the present).

The Calendar class provides many member constants that represent given calendar fields:

field value meaning
YEAR Year
MONTH Month (starts from 0, can be used with +1)
DAY_OF_MONTH Day of the month (day)
HOUR Hours (12-hour format)
HOUR_OF_DAY Hours (24-hour format)
MINUTE point
SECOND Second
DAY_OF_WEEK Day of the week (day of the week, Sunday is 1, can be used with -1)

1. get/set method

The get method is used to obtain the value of the specified field, and the set method is used to set the value of the specified field. The code example is as follows:

import java.util.Calendar;
public class Demo {
    public static void main(String[] args) {
        // 创建Calendar对象
        Calendar cal = Calendar.getInstance();
        // 获取年 
        int year = cal.get(Calendar.YEAR);
        // 获取月
        int month = cal.get(Calendar.MONTH) + 1;
        // 获取日
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

        System.out.print(year + "年" + month + "月" + dayOfMonth + "日");
    }
}
import java.util.Calendar;

public class Demo07CalendarMethod {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        // 设置年
        cal.set(Calendar.YEAR, 2023);
        // 获取年
        int year = cal.get(Calendar.YEAR);
        // 获取月
        int month = cal.get(Calendar.MONTH) + 1;
        // 获取日
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

        System.out.print(year + "年" + month + "月" + dayOfMonth + "日");
    }
}

2. add method

The add method can add and subtract the value of the specified calendar field. If the second parameter is a positive number, the offset is added, and if it is a negative number, the offset is subtracted. Code such as:

import java.util.Calendar;

public class Demo08CalendarMethod {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        // 获取年
        int year = cal.get(Calendar.YEAR);
        // 获取月
        int month = cal.get(Calendar.MONTH) + 1;
        // 获取日
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        System.out.println(year + "年" + month + "月" + dayOfMonth + "日");

        // 使用add方法
        cal.add(Calendar.DAY_OF_MONTH, 5); // 加5天
        cal.add(Calendar.YEAR, -2); // 减2年
        // 获取年
        year = cal.get(Calendar.YEAR);
        // 获取月
        month = cal.get(Calendar.MONTH) + 1;
        // 获取日
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        System.out.println(year + "年" + month + "月" + dayOfMonth + "日");
    }
}

3. getTime method: returns the corresponding Date object

The getTime method in Calendar does not get the millisecond time, but the corresponding Date object.

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

public class Demo {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        System.out.println(date); 
    }
}

Precautions:

  1. The Western week starts on Sunday (1) and Monday (2), and the Chinese week starts on Monday, so -1 can be used.
  2. In the Calendar class, the month is represented by 0-11 representing January-December (+1 can be used).
  3. The date is related to the size. The later the time, the larger the time.

Summarize

 Java used Date to calculate time in the early days. Later, most of the methods of the Date class became obsolete, and it turned to the Calendar class to replace the Date class. However, the Calendar class was also unsatisfactory. Therefore, this article specifically summarizes and summarizes the basic concepts, common operations and related classes of the Date class in Java to facilitate future development. I hope it will be helpful to everyone.

Guess you like

Origin blog.csdn.net/Clearlove_S7/article/details/130442197