Table of contents
1Date class
1.1 Overview
java.util.Date
Class represents a specific instant of time, accurate to milliseconds. The constructor of the Date class can convert millisecond values into date objects .
1.2 Date class construction method
public Date()
: Allocates a Date object and initializes this object to represent the time (accurate to milliseconds) at which it was allocated.public Date(long date)
: Allocates and initializes a Date object to represent the specified number of milliseconds since a standard base time called the "epoch", January 1, 1970 00:00:00 GMT.
tips: Since we are in the East Eighth District, our base time is 8:00:00 on January 1, 1970.
To put it simply: using no-parameter construction, you can automatically set the millisecond time of the current system time; specifying long type construction parameters can customize the millisecond time. For example:
import java.util.Date;
public class DemoDate {
public static void main(String[] args) {
// 创建日期对象,把当前的时间转成日期对象
System.out.println(new Date()); // Sat Sep 19 23:11:21 CST 2020
// 创建日期对象,把当前的毫秒值转成日期对象
System.out.println(new Date(0L)); // Thu Jan 01 08:00:00 CST 1970
}
}
Tips: When using the println method, the toString method in the Date class will be automatically called. The Date class overrides and rewrites the toString method in the Object class, so the result is a string in the specified format.
1.3 getTime method of Date class: returns the number of milliseconds
2 DateFormat class
java.text.DateFormat
It 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.1 The construction method of its subclass SimpleDateFormat
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) {
// 对应的日期格式如:2018-01-16 15:06:38
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:
public String format(Date date)
: Format the Date object into a string.public Date parse(String source)
: Parse the string into a Date object.
2.2.1 format method
The code using the format method is:
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.2.2 parse method
The code using the parse method is:
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 = "2018年12月11日";
Date date = df.parse(str);
System.out.println(date); // Tue Dec 11 00:00:00 CST 2018
}
}
2.3 Comprehensive exercises
Question : Please use the date and time related API to calculate how many days a person has been born.
Idea:
1. Get the millisecond value corresponding to the current time
2. Get the millisecond value corresponding to your birth date
3. Subtract two times (current time – date of birth)
Code:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
/*
把String转换成Date对象
*/
public class Demo {
public static void main(String[] args) throws ParseException {
System.out.println("请输入出生日期 格式 YYYY-MM-dd");
// 获取出生日期,键盘输入
String birthdayString = new Scanner(System.in).next();
// 将字符串日期,转成Date对象
// 创建SimpleDateFormat对象,写日期模式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 调用方法parse,字符串转成日期对象
Date birthdayDate = sdf.parse(birthdayString);
// 获取今天的日期对象
Date todayDate = new Date();
// 将两个日期转成毫秒值,Date类的方法getTime
long birthdaySecond = birthdayDate.getTime();
long todaySecond = todayDate.getTime();
long secone = todaySecond-birthdaySecond;
if (secone < 0){
System.out.println("还没出生呢");
} else {
System.out.println(secone/1000/60/60/24);
}
}
}
请输入出生日期 格式 YYYY-MM-dd
2019-09-12
373
3 Calendar class
3.1 Concept
java.util.Calendar
It 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.
3.2 How to obtain
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();
}
}
3.3 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)
: Adds or subtracts the specified amount of time to a given calendar field according to the calendar's rules.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) |
3.3.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. Code usage demonstration:
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 + "日");
}
}
2020年9月20日
import java.util.Calendar;
public class Demo07CalendarMethod {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
// 设置年
cal.set(Calendar.YEAR, 2018);
// 获取年
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 + "日");
}
}
2018年9月20日
3.3.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, 2); // 加2天
cal.add(Calendar.YEAR, -3); // 减3年
// 获取年
year = cal.get(Calendar.YEAR);
// 获取月
month = cal.get(Calendar.MONTH) + 1;
// 获取日
dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
System.out.println(year + "年" + month + "月" + dayOfMonth + "日");
}
}
2020年9月20日
2017年9月22日
3.3.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);
}
}
Sun Sep 20 08:44:18 CST 2020
Tips:
The Western week starts on Sunday (1) and Monday (2), and the Chinese week starts on Monday, so -1 can be used.
In the Calendar class, the month is represented by 0-11 representing January-December (+1 can be used).
The date is related to the size. The later the time, the larger the time.