catalogue
1, Date class
1. Overview
java.util.Date: class representing date and time
Class Date represents a specific moment, accurate to milliseconds.
Milliseconds: thousandth of a second 1000 milliseconds = 1 second
A specific moment: a point in time, a moment in time
2088-08-08 09:55:33:333 instant
2088-08-08 09:55:33:334 instant
2088-08-08 09:55:33:334 instant
...
Millisecond value: it can calculate time and date
How many days are there between October 7, 2020 and January 20, 2022
You can convert the date into milliseconds for calculation. After calculation, you can convert milliseconds into dates
Convert date to milliseconds:
Current date: 2088-01-01
Time origin (0 ms): January 1, 1970 00:00:00 (Greenwich, UK)
This is to calculate the total number of milliseconds (3742767540068L) between the current date and the time origin
Note:
China belongs to the East eighth District, which will increase the time by 8 hours
January 1, 1970 08:00:00
Convert milliseconds to date:
1 day = 24 × sixty × 60 = 86400 seconds = 86400 x 1000 = 86400000 milliseconds
2. Common methods
java. util. The date class represents a specific moment, accurate to milliseconds.
public Date() allocates a Date object and initializes it to represent the time (in milliseconds) at which it was allocated.
import java.util.Date; public class Demo01Date { public static void main(String[] args) { // Create a date object and put the current time System.out.println(new Date()); // Tue Jan 20 14:37:35 CST 2022 // Create a date object and convert the current millisecond value into a date object System.out.println(new Date(0L)); // Thu Jan 01 08:00:00 CST 1970 } }
import java.util.Date; public class Demo02Date { public static void main(String[] args) { demo(); } /* long getTime() Convert the date to a millisecond value (equivalent to the System.currentTimeMillis() method) Returns the number of milliseconds represented by this Date object since January 1, 1970, 00:00:00 GMT. */ private static void demo() { Date date = new Date(); long time = date.getTime(); System.out.println(time); //1642667329975 } }
import java.util.Date; public class test { public static void main(String[] args) { Date d = new Date(); System.out.println(d.toLocaleString()); // January 20, 2022 8:01:46 PM } }
2, DateFormat class
1. Overview
java.text.DateFormat: is an abstract class of date / time formatting subclass
Function:
Formatting (i.e. date - > text), parsing (text - > date)
Member method:
String format(Date date) formats the Date into a string matching the pattern according to the specified pattern
Date parse(String source) parses the string conforming to the pattern into a date date
DateFormat class is an abstract class and cannot be used to create objects directly. You can use the subclass of DateFormat class
java.text.SimpleDateFormat extends DateFormat
Construction method:
SimpleDateFormat(String pattern)
Construct a SimpleDateFormat with the date format symbols of the given schema and the default locale.
Parameters:
String pattern: pass the specified pattern
Mode: case sensitive
y # year
M # month
d) day
H +
m , min
S} s
Writing the corresponding pattern will replace the pattern with the corresponding date and time
"yyyy-MM-dd HH:mm:ss"
Note:
The letters in the mode cannot be changed, and the symbols of the connection mode can be changed
"yyyy MM dd HH h mm min ss s"
2. Construction method
3. Format Rules
Identification letters (case sensitive) | meaning |
y | year |
M | month |
d | day |
H | Time |
m | branch |
s | second |
import java.text.DateFormat; import java.text.SimpleDateFormat; public class Demo02SimpleDateFormat { public static void main(String[] args) { // The corresponding date format is as follows: 2022 ‐ 01 ‐ 20 15:06:38 DateFormat format = new SimpleDateFormat("yyyy‐MM‐dd HH:mm:ss"); } }
4. Common methods
(1) format method
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /*Convert Date object to String */ public class Demo03DateFormatMethod { public static void main(String[] args) { Date date = new Date(); // Create a date format object. You can specify the style when obtaining the format object DateFormat df = new SimpleDateFormat("yyyy year MM month dd day"); String str = df.format(date); System.out.println(str); // January 20, 2020 } }
(2) parse method
Use the parse method in the DateFormat class to parse the text into a date
Use steps:
1. Create a SimpleDateFormat object and pass the specified pattern in the constructor
2. Call the parse method in the SimpleDateFormat object to parse the string that conforms to the pattern in the construction method into a Date date
Note:
public Date parse(String source) throws ParseException
The parse method declares an exception called ParseException parsing exception
If the pattern of string and constructor is different, the program will throw this exception
When calling a method that throws an exception, you must handle the exception. Either throw continues to throw the exception, or try catch handles the exception itself
import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /*Convert String to Date object */ public class Demo04DateFormatMethod { public static void main(String[] args) throws ParseException { DateFormat df = new SimpleDateFormat("yyyy year MM month dd day"); String str = "2022 January 20"; Date date = df.parse(str); System.out.println(date); // Thu Jan 20 00:00:00 CST 2022 } }
3, Practice
practice:
Please use the date and time related API to calculate how many days a person has been born.
1. Use the method next in the Scanner class to get the date of birth
2. Use the parse method in the DateFormat class to parse the birth Date of the string into the birth Date in Date format
3. Converts the Date of birth in Date format to a millisecond value
4. Gets the current date and converts it to a millisecond value
5. Use the millisecond value of the current date - the millisecond value of the birth date
6. Convert millisecond difference to days (s/1000/60/60/24)
public static void function() throws Exception { System.out.println("Please enter birth date format YYYY‐MM‐dd"); // Get the date of birth and enter it with the keyboard String birthdayString = new Scanner(System.in).next(); // Convert a Date string to a Date object // Create a SimpleDateFormat object to write the date pattern SimpleDateFormat sdf = new SimpleDateFormat("yyyy‐MM‐dd"); // Call the parse method to convert the string into a date object Date birthdayDate = sdf.parse(birthdayString); // Get today's Date object Date todayDate = new Date(); // Convert the two dates into millisecond values, and the method getTime of the Date class long birthdaySecond = birthdayDate.getTime(); long todaySecond = todayDate.getTime(); long secone = todaySecond‐birthdaySecond; if (secone < 0){ System.out.println("Not yet born"); } else { System.out.println(secone/1000/60/60/24); } }
4, Calendar Class
1. Concept
2. Acquisition method
import java.util.Calendar; public class Demo06CalendarInit { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); } }
3. Common methods
field value | meaning |
YEAR
| year |
MONTH | Month (starting from 0, can be used with + 1) |
DAY_OF_MONTH | Day (day) of the month |
HOUR | Hour (12 hour system) |
HOUR_OF_DAY | Hour (24-hour system) |
MINUTE | branch |
SECOND | second |
DAY_OF_WEEK | Day of the week (day of the week, Sunday is 1, can be - 1) |
import java.util.Calendar; import java.util.Date; /* Calendar Common member methods of class: 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 for 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). Parameters of member method: int field:The fields of Calendar class can be obtained by using the static member variable of Calendar class public static final int YEAR = 1; year public static final int MONTH = 2; month public static final int DATE = 5; One day in the middle of the month public static final int DAY_OF_MONTH = 5;One day in the middle of the month public static final int HOUR = 10; Time public static final int MINUTE = 12; branch public static final int SECOND = 13; second */ public class Demo02Calendar { public static void main(String[] args) { demo01(); System.out.println("=============="); demo02(); System.out.println("=============="); demo03(); System.out.println("=============="); demo04(); } /* public Date getTime(): Returns a Date object representing this Calendar time value (the millisecond offset from the epoch to the present). Convert calendar object to date object */ private static void demo04() { //Use the getInstance method to get the Calendar object Calendar c = Calendar.getInstance(); Date date = c.getTime(); System.out.println(date); // Thu Jan 20 19:41:43 CST 2022 } /* public abstract void add(int field, int amount): Adds or subtracts the specified amount of time for a given calendar field according to the rules of the calendar. Increases / decreases the specified field by the specified value Parameters: int field:Pass the specified calendar field (YEAR,MONTH...) int amount:Increases / decreases the specified value Positive: increase Negative: decrease */ private static void demo03() { //Use the getInstance method to get the Calendar object Calendar c = Calendar.getInstance(); //Increase the year by two years c.add(Calendar.YEAR,2); //Reduce the month by three months c.add(Calendar.MONTH,-3); int year = c.get(Calendar.YEAR); System.out.println(year); int month = c.get(Calendar.MONTH); System.out.println(month);//Month 0-11 in the West and 1-12 in the East //int date = c.get(Calendar.DAY_OF_MONTH); int date = c.get(Calendar.DATE); System.out.println(date); } /* public void set(int field, int value): Sets the given calendar field to the given value. Parameters: int field:Pass the specified calendar field (YEAR,MONTH...) int value:The value set for the specified field */ private static void demo02() { //Use the getInstance method to get the Calendar object Calendar c = Calendar.getInstance(); //Set year to 9999 c.set(Calendar.YEAR,9999); //Set month to September c.set(Calendar.MONTH,9); //Set day 9 c.set(Calendar.DATE,9); //At the same time, set the month, year and day. You can use the overload method of set c.set(8888,8,8); int year = c.get(Calendar.YEAR); System.out.println(year); int month = c.get(Calendar.MONTH); System.out.println(month);//Month 0-11 in the West and 1-12 in the East int date = c.get(Calendar.DATE); System.out.println(date); } /* public int get(int field): Returns the value of the given calendar field. Parameter: pass the specified calendar field (YEAR,MONTH...) Return value: the specific value represented by the calendar field */ private static void demo01() { //Use the getInstance method to get the Calendar object Calendar c = Calendar.getInstance(); int year = c.get(c.YEAR); System.out.println(year); int month = c.get(Calendar.MONTH); System.out.println(month);//Month 0-11 in the West and 1-12 in the East //int date = c.get(Calendar.DAY_OF_MONTH); int date = c.get(Calendar.DATE); System.out.println(date); } }