Java:Date类

There are two Date classes in Java. We are talking about the Date class under the java.util package, so when using this class, you need to be careful not to lead the wrong package.

Construction method:

	//1、获取当前系统时间
	public Date();

	//2、参数传入自1970 年 1 月 1 日 00:00:00 GMT)以来的指定毫秒数
	//获取经过该毫秒数的时间
	Date(long date);

Common methods:

getTime(): Returns the number of milliseconds represented by this Date object since January 1, 1970 00:00:00 GMT.

toString(): Convert the Date object to a string.
For example: Thu Jan 21 12:31:47 CST 2021

Convert string to Date

1. Create a date string
String strDate = "2021年01月21日 12:37:26 218";
2. Pass parameters, and the formatted date format needs to be consistent with the time format in the string
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
3. Call the parse() method to convert to date
Date date = sdf.parse(strDate);
4. View the result
Thu Jan 21 12:37:26 CST 2021

Date formatting:

Here we are using the SimpleDateFormat class
1. Create a SimpleDateFormat object, pass in the date format string you want to set in the constructor parameter
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
2. Call the format method, pass in the Date type date, and return the formatted string date format
String strTime = sdf.format(now);
3. View the results
2021年01月21日 12:37:26 218

Guess you like

Origin blog.csdn.net/qq_41504815/article/details/112966246