Time class
Date
SimpleDateFormat
JDK8 new date class
Exception class
Exception overview
Exception handling method
Custom exception
time
Time in life
There is no unified standard for the time of each country. They all calculate their own time, okay?
The answer is No
World standard time
Greenwich mean time (GMT)
There are errors, which are no longer used as a basis at present
atomic clock
Two million years, one second error
Standard time in China
Beijing time, at + 8 hours of world standard time (we are in the East 8 District)
Time conversion formula
Common = 1000 ms
1 MS = 1000 ms
1 = 1000 nanoseconds
Time origin in computer (also known as starting time)
January, 1970 00:00:00
reason
In August 1960, Bell Labs programmers developed a version of Unix on the old PDP-7 machine using B language
Subsequently, the B language was improved, the C language was developed, and UNIX was rewritten
Therefore, I think January 1, 1970 is the birthday of C language, and Java continues this tradition
The millisecond value obtained by the following code is the millisecond value from January 1, 1970 to the code running time
long time = System.currentTimeMillis();
System.out.println(time); //1644254175148
Date
Date represents a specific time, accurate to milliseconds
Construction method (note that the date under util package is currently used)
public Date(); Create a date object that represents the default (system) time
public Date(long date); Create a date object that represents the specified time
//public Date(); Create a date object that represents the default (system) time Date d1 = new Date(); System.out.println(d1); //Tue Feb 08 16:08:50 CST 2022 //public Date(long date); Create a date object that represents the specified time Date d2 = new Date(0L); System.out.println(d2); //Thu Jan 01 08:00:00 CST 1970 (with 8-hour time difference) //It means 9 a.m. on January 1, 1970 Date d3 = new Date(3600 * 1000L); System.out.println(d3); //Thu Jan 01 09:00:00 CST 1970
Date member method
public long getTime(); Gets the millisecond value of the time object
public void setTime(long time); Set the time and pass the millisecond value
//public long getTime(); Gets the millisecond value of the time object Date d1 = new Date(); //Gets the millisecond value represented by the time object long t1 = d1.getTime(); System.out.println(t1); //1644308106562 //It should be the same as the millisecond value represented by system time long t2 = System.currentTimeMillis(); System.out.println(t2); //1644308106562 //public void setTime(long time); Set the time and pass the millisecond value //It is simply understood as the modification time Date d2 = new Date(); //Set as time origin (with 8-hour time difference) d2.setTime(0L); System.out.println(d2); //Thu Jan 01 08:00:00 CST 1970
Time date class - SimpleDateFormat
SimpleDateFormat can format and parse Date objects
Format: Date object - > January 1, 2020 00:00:00
Resolution: "January 1, 2020 00:00:00" - > Date object
The letters in API and their corresponding relationships are as follows
y # year
M # month
d # day
H = hour
m # min
s , sec
Examples of common formats
2020-11-11 13:27:06 -> yyyy-MM-dd HH:mm:ss
November 11, 2020 13:27:06 - > yyyy dd HH:mm:ss
SimpleDateFormat constructor
public SimpleDateFormat(); Construct a simpledateformat object and use the default format
public SimpleDateFormat(String format); Construct a SimpleDateFormat object using the specified format
SimpleDateFormat formatting and parsing methods
public final String format(Date date); Format to specified format
public Date parse(String source); Resolves to a date object from the specified format
// //public SimpleDateFormat(); Construct a simpledateformat object and use the default format public class Demo01 { public static void main(String[] args) { //SimpleDateFormat sdf = new SimpleDateFormat(); // Use default format //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day"); //Format time, using default format String format = sdf.format(new Date()); System.out.println(format); /* Specify a different format for formatting 2022/2/8 4:40 pm 2022-02-08 16:42:37 2022 February 8 */ } } // public Date parse(String source); Resolves to a date object from the specified format public class Demo02 { public static void main(String[] args) throws ParseException { //Provide parsed text String s = "2022 January 1, 2011:11"; //public Date parse(String source); Resolves to a date object from the specified format //Simpledateformat SDF = new simpledateformat ("yyyy MM DD HH:mm"); /* If the specified format is different from the format to be parsed, an error is reported: java.text.ParseException */ SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm"); Date date = sdf.parse(s); System.out.println(date); //Sat Jan 01 11:11:00 CST 2022 } }
practice
/* Start time: 0:0:0, November 11, 2020 End time: 0:10:0, November 11, 2020 Zhang San 0:03:47, November 11, 2020 (second kill successful) Li Si 0:10:11, November 11, 2020 (second kill failed) Time node */ public class Demo { public static void main(String[] args) throws ParseException { //The parsing format is the same SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss"); //Parse the start and end times and get the value in milliseconds long startTime = sdf.parse("2020 November 11, 2014 0:0:0").getTime(); long endTime = sdf.parse("2020 November 11, 2014 0:10:0").getTime(); //Parse the time of Zhang San and Li Si and obtain the millisecond value long zhangsan = sdf.parse("2020 November 11, 2014 0:03:47").getTime(); long lisi = sdf.parse(" 2020 November 11, 2014 0:10:11").getTime(); //judge if(zhangsan >= startTime && zhangsan <= endTime){ System.out.println("Zhang San succeeded in second kill!"); }else { System.out.println("Zhang San failed in the second kill!"); } if(lisi >= startTime && lisi <= endTime){ System.out.println("Li Si succeeded in second kill!"); }else { System.out.println("Li Si failed in the second kill!"); } } }
JDK8 time class
In JDK8, the Date object is split
1. LocalDate: indicates the date (month, year, day)
2. LocalTime: represents the time (hour, minute and second)
3. LocalDateTime: represents time + date (mm / DD / yyyy, H / min / s)
//public static LocalDateTime now(); Get current system time LocalDateTime date1 = LocalDateTime.now(); System.out.println(date1); //2022-02-08T18:19:10.196345700 //Public static LocalDateTime of (year, month, day, hour, minute, second); Initialize the LocalDateTime object according to the parameters //LocalDateTime date2 = LocalDateTime.of(2022, 15, 2, 22, 22, 22); /* If the month exceeds the specified range, an error is reported: java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 15 */ LocalDateTime date2 = LocalDateTime.of(2022, 2, 2, 22, 22, 22); System.out.println(date2); //2022-02-02T22:22:22
LocalDateTime get method
public int getYear(); Acquisition year
public int getMonthValue(); Get month (1-12)
* Month getMonth(); Get the month return value as enumeration
public int getDayOfMonth(); Get the day of the month (1-31)
public int getDayOfYear(); Get the day of the year (1-366)
public DayOfWeek getDayOfWeek(); Get day of week
public int getMinute(); Get minutes
public int getHour(); Get hours
//Create time object LocalDateTime date = LocalDateTime.of(2022, 11, 11, 11, 11, 11); //public int getYear(); Acquisition year System.out.println(date.getYear()); //2022 //public int getMonthValue(); Get month (1-12) System.out.println(date.getMonthValue()); //11 //* Month getMonth(); Get the month return value as enumeration System.out.println(date.getMonth()); //NOVEMBER //public int getDayOfMonth(); Get the day of the month (1-31) System.out.println(date.getDayOfMonth()); //11 //public int getDayOfYear(); Get the day of the year (1-366) System.out.println(date.getDayOfYear()); //315 //public DayOfWeek getDayOfWeek(); Get week System.out.println(date.getDayOfWeek()); //FRIDAY //public int getMinute(); Get minutes System.out.println(date.getMinute()); //11 //public int getHour(); Get hours System.out.println(date.getHour()); //11
JDK8 time class - conversion method
From LocalDateTime object to LocalDate and LocalTime
public LocalDate toLocalDate();
public LocalTime toLocalTime();
//Create time object LocalDateTime date = LocalDateTime.of(2022, 2, 2, 22, 22, 22); //public LocalDate toLocalDate(); System.out.println(date.toLocalDate()); //2022-02-02 //public LocalTime toLocalTime(); System.out.println(date.toLocalTime()); //22:22:22
JDK8 time class - formatting and parsing
Formatting and parsing methods
Public string format (specify format); Format LocalDateTime as a string
Public LocalDateTime (string to be parsed, parsing format); Parses the specified string as a LocalDateTime object
public static DateTimeFormatter ofPattern(String pattern); Get date formatter (JDK8)
JDK8 time class - Method of plus series
LocalDateTime Ways to increase and reduce time public LocalDateTime plusYears(long years); Increase or decrease last year public LocalDateTime plusMonths(long months); Add or subtract months public LocalDateTime plusDays(long days); Add or subtract days public LocalDateTime plusHours(long hours); When adding or subtracting public LocalDateTime plusMinutes(long minutes); Add or subtract points public LocalDateTime plusSeconds(long seconds); Add or subtract seconds public LocalDateTime plusWeeks(long weeks); Add or subtract weeks
Note: passing a positive number is an increase and passing a negative number is a subtraction
JDK8 time class - Method of minus series (opposite to plus Series)
public LocalDateTime minusYears(long years); Increase or decrease last year public LocalDateTime minusMonths(long months); Add or subtract months public LocalDateTime minusDays(long days); Add or subtract days public LocalDateTime minusHours(long hours); When adding or subtracting public LocalDateTime minusMinutes(long minutes); Add or subtract points public LocalDateTime minusSeconds(long seconds); Add or subtract seconds public LocalDateTime minusWeeks(long weeks); Add or subtract weeks
JDK8 time class - Method of with series
public LocalDateTime withYears(long years); Direct modification year public LocalDateTime withMonths(long months); Direct modification month public LocalDateTime withDays(long days); Direct modification date public LocalDateTime withHours(long hours); When modifying directly public LocalDateTime withMinutes(long minutes); Directly modify score public LocalDateTime withSeconds(long seconds); Directly modify seconds public LocalDateTime withWeeks(long weeks); Directly modify week
JDK8 time class - time interval object
Time interval object period (mm / DD / yyyy)
Public static period between (start time, end time); Calculate the interval between two "times", including month, year and day
getYears(); Acquisition year
getMonths(); Get month
getDays(); Acquisition day
//Object creation date LocalDate date1 = LocalDate.of(2022, 1, 1); LocalDate date2 = LocalDate.of(2023, 12, 12); //Get interval object Period between = Period.between(date1, date2); System.out.println(between); /* P1Y11M11D P: Interval object Period 1Y: 1 year 11M: 11 Months 11D: 11 day */ //Get date System.out.println(between.getYears()); //1 System.out.println(between.getMonths()); //11 System.out.println(between.getDays()); //11 //Get total months System.out.println(between.toTotalMonths()); //23
Time interval object duration (seconds, milliseconds, nanoseconds)
Public static duration between (start time, end time); Calculate the interval between two "times", including seconds, milliseconds and nanoseconds
toSeconds(); Get seconds
toMillis(); Get milliseconds
toNanos(); Get nanoseconds
//Create time object LocalDateTime date1 = LocalDateTime.of(2022, 1, 1, 12, 0, 0); LocalDateTime date2 = LocalDateTime.of(2023, 12, 12, 12, 30, 30); //Get interval object Duration duration = Duration.between(date1, date2); System.out.println(duration); /* PT17040H30M30S PT: Interval object 17040H: 17040 Hours 30M: 30 minute 30S: 30 second */ //Get seconds, milliseconds, nanoseconds System.out.println(duration.toSeconds()); //61345830 System.out.println(duration.toMillis()); //61345830000 System.out.println(duration.toNanos()); //61345830000000000
Summary:
LocalDate: indicates the date (month, year, day)
LocalTime: represents the time (hour, minute and second)
LocalDateTime: represents time + date (mm / DD / yyyy, H / min / s)
LocalDateTime - transfer - > localdate - use - > tolocaldate(); method
LocalDateTime - transfer - > Localtime - use - > tolocaltime(); method
Create time object - > now(); Get (current system) time object
-> of(); Get (specify) time object
Get the year, month, day, hour, minute and second in the time object
Format - > format
Parse - > parse
Methods to increase or decrease time - > start with plus and start with minus
Modify time - > start with
Time interval - > period operation date
- > duration operation seconds, milliseconds, nanoseconds
Abnormal
What is an exception?
Exceptions are used to describe problems in code
be careful!
Grammatical errors are not counted in the exception system
Abnormal system?
- Throwable
- Error: serious Error, such as memory overflow
- Exception: Exception class, which represents the problem that the program itself can handle
- RuntimeException: runtime exception (such as null pointer exception, index out of bounds exception)
- all exceptions except RuntimeException: compile time exception (exception that must be handled during compilation, otherwise it will not pass compilation, such as formatting exception)
int[] arr = {1,2,3}; //System.out.println(arr[3]); //java.lang.ArrayIndexOutOfBoundsException arr = null; //System.out.println(arr[0]); //java.lang.NullPointerException SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day"); //sdf. Parse ("January 1, 2020")// java.text.ParseException
By default, the virtual machine handles exceptions
Why does the console have such a red font? Who printed it?
- when an exception occurs in the code, an exception object will be created where the exception occurs
- first, check whether the program has its own code to handle exceptions (no)
- give it to the caller of this method for handling (the caller of the main method is the JVM, and finally give it to the JVM to handle the exception)
- the JVM handles exceptions by default
1. Prompt the exception information on the console in red font
2. Stop the program when an exception occurs, and the subsequent code will not be executed
throws declaration exception
Exception handling method 1: throws: throws exception class name
Note: it is written at the definition of the method to declare an exception (this exception may occur when calling me)
public class Demo { public static void main(String[] args) throws ParseException { //2. At this time, the caller does not handle it, or does he leave it to the JVM for processing //method01(); //java.lang.NullPointerException //4. throws ParseException: indicates that the caller has not processed it, and finally handed it to the JVM for default processing method02(); //java.text.ParseException } //3. throws ParseException: indicates that there may be exceptions in this method, which should be handled by the caller private static void method02() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day"); sdf.parse("2020-1 January 1"); } //1. throws NullPointerException: indicates that there may be exceptions in this method, which should be handled by the caller private static void method01() throws NullPointerException { int[] arr = null; System.out.println(arr[0]); //java.lang.NullPointerException } }
Precautions for declaring exceptions
Follow up NullPointerException and find that it inherits from RuntimeException, so it is a runtime exception
Follow up ParseException and find that it inherits from Exception, so it is a compile time Exception
Precautions for declaring exceptions
If it is a runtime exception: do not write can be omitted - > method01 omit throws NullPointerException, and no error is reported
If it is a compile time exception: the declaration must be displayed, otherwise the code continues to report an error - > method02 omits throws ParseException to report an error
public class Demo { public static void main(String[] args) throws ParseException { method01(); method02(); } // Compile time exceptions cannot be omitted without writing private static void method02() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day"); sdf.parse("2020-1 January 1"); } private static void method01(){ int[] arr = null; System.out.println(arr[0]); //java.lang.NullPointerException } }
throw throws an exception
reflection?
There was an exception before. The virtual machine helped us create an exception object and threw it to the caller
But if we need to create an exception object manually, how do we implement it?
Exception handling method 2: throw
throw new exception();
Note: this format is in the method, which means that the current code throws an exception manually, and the following code will not be executed
The difference between throws and throw
1. throws: used after the method declaration, followed by the exception class name, indicating that the declared exception may occur when calling the method
2. throw: used in the method body, followed by the exception object name (new), indicating that an exception is thrown manually and handled by the statement in the method body
public class Demo01 { public static void main(String[] args) { System.out.println("There is a beautiful wife at home"); System.out.println("And an official brother"); System.out.println("I have another business"); System.out.println("Do you want to live like this?"); /* Throw (create) an exception manually and leave it to the caller for processing The following code will not be executed */ throw new RuntimeException(); //System.out.println("Wu Dalang's standard life"); } }
Why throw an exception? Because the execution result should be fed back to the caller
public class Demo02 { public static void main(String[] args) { int[] arr = null; printArr(arr); //4. If the caller doesn't handle it, he still throws it to the JVM for default processing //5. Console print exception information: Java lang.NullPointerException //6. Next, learn how to handle exceptions! } public static void printArr(int[] arr){ if(arr== null){ //1. Question: does the caller know that it has been printed successfully? //2. Answer: I don't know, because the method just prints the result on the console and doesn't feed back a result to the caller //System.out.println("parameter cannot be null"); //3. Code improvement: manually throw an exception to the caller, and the caller will get feedback throw new NullPointerException(); }else { for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } } }
try...catch handles exceptions by itself
Exception handling method 3: try catch
try{
Codes with possible exceptions;
} catch (exception class name variable name){
Code for handling exceptions;
}
Shortcut keys: Ctrl + Alt + T, select the corresponding operation and modify the corresponding code
public static void main(String[] args) { int[] arr = null; //2. Handle exceptions manually try { printArr(arr);//Possible exception codes } catch (NullPointerException e) { System.out.println("Parameter cannot be null null"); //Code to handle exceptions } //3. Advantages of this method: after possible exceptions, the correct code can continue to run! System.out.println("See if we can do it..."); } public static void printArr(int[] arr){ if(arr== null){ //1. Throw an exception to the caller throw new NullPointerException(); }else { for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }
try... Frequently asked questions about catch
try... Frequently asked questions about catch
1. If there is no problem in the try, how to execute it?
All the code in try will be executed, and the code in catch will not be executed
Continue to execute the following correct code
2. If there is a problem in try, will the code below try still be executed?
Stop where you encounter problems in try and directly enter the corresponding catch execution code
Continue to execute the following correct code
3. If the problem is not captured, how does the program run?
try...catch is equivalent to not writing, and the exception is handled by the caller
Default processing method of JVM (console error)
4. How to deal with multiple exceptions that may occur at the same time?
Write multiple catches to catch different exceptions that may occur
Note: if multiple exceptions have child parent relationship, the parent should be written below
Reason: the code will be corrected according to the writing order of catch. If the parent class is above, the child class exception can be received
Question? Can you write only one catch to directly catch the Exception of the parent class
Not recommended! Because we usually have different solutions for different exceptions!
try { Scanner sc = new Scanner(System.in); System.out.println("Please enter your age:"); String line = sc.nextLine(); //First exception int age = Integer.parseInt(line); System.out.println(age); //Second exception System.out.println(2 / 0); } catch (NumberFormatException e) { System.out.println("Formatting exception..."); //Catch can write multiple to catch different exceptions } catch (ArithmeticException e) { System.out.println("Abnormal mathematical operation..."); //Catch can write multiple to catch different exceptions } System.out.println("I am try...catch Later code..."); try { Scanner sc = new Scanner(System.in); System.out.println("Please enter your age:"); String line = sc.nextLine(); //Input error data: aaa int age = Integer.parseInt(line); System.out.println(age); System.out.println("I am try Code in..."); //Do not execute } catch (NullPointerException e) { //The problem has not been captured, try Catch is equivalent to no writing, and the JVM performs the default processing method System.out.println("I am catch Code in..."); //Do not execute } System.out.println("I am try...catch Later code..."); //Do not execute try { Scanner sc= new Scanner(System.in); System.out.println("Please enter your age:"); String line = sc.nextLine(); //Input error data: aaa int age = Integer.parseInt(line); System.out.println(age); System.out.println("I am try Code in..."); //Do not execute } catch (NumberFormatException e) { System.out.println("I am catch Code in..."); //implement } System.out.println("I am try...catch Later code..."); //implement try { Scanner sc = new Scanner(System.in); System.out.println("Please enter your age:"); String line = sc.nextLine(); //Enter correct data: 18 int age = Integer.parseInt(line); System.out.println(age); System.out.println("I am try Code in..."); //implement } catch (NumberFormatException e) { System.out.println("I am catch Code in..."); } System.out.println("I am try...catch Later code..."); //implement }
throwable member method
throwable member method
1. public String getMessage(); Returns a detailed message string
2. public String toString(); Return short description
3. public void printStackTrace(); Print the exception error message on the console (in red font. Note that the default processing method of the JVM here is different!)
public static void main(String[] args) { try { int[] arr = {1,2,3}; System.out.println(arr[3]); } catch (ArrayIndexOutOfBoundsException e) { //1. public String getMessage(); Returns a detailed message string //String message = e.getMessage(); //System.out.println(message); //Index 3 out of bounds for length 3 //2. public String toString(); Return short description //String s = e.toString(); //System.out.println(s); //java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 //3. public void printStackTrace(); //Print the exception error message on the console (in red font. Note that the default processing method of the JVM here is different!) e.printStackTrace(); } System.out.println("Did I do it?If I do,Then it's with JVM The default processing method is different!"); }
Unusual little exercise
Requirements:
Enter the student's name and age on the keyboard. The age range is 18-25
Abnormal data beyond this range cannot be assigned and needs to be re entered until it is correct
//Student class public class Student { ... public void setAge(int age) { if (age >= 18 && age <= 25) { this.age = age; } else { //If the age is wrong, throw a runtime exception throw new RuntimeException("Age out of range!"); } } ... } //Test class public class Demo { public static void main(String[] args) { //Create student and keyboard objects Student stu = new Student(); Scanner sc = new Scanner(System.in); //Prompt to enter name, receive and assign value System.out.println("Please enter your name:"); String name = sc.nextLine(); stu.setName(name); //Cycle to enter the age until it is correct while (true) { System.out.println("Please enter age:"); String line = sc.nextLine(); try { //Code with possible exceptions int age = Integer.parseInt(line); stu.setAge(age); //Dead circulation outlet break; } catch (NumberFormatException e) { //Capture conversion exception System.out.println("Please enter an integer"); } catch (RuntimeException e) { //Catch the exception thrown by the set method System.out.println("Please enter a legal age"); } } System.out.println("Information entered successfully,Program end!"); } }
Custom exception
To customize exceptions
1. Define an exception class. See the meaning of the name for the class name
2. Inheritance relationship, general inheritance, runtime exception
3. Provide null and band parameter structures
Code example
public class AgeOutOfBoundsException extends RuntimeException{ public AgeOutOfBoundsException() { } public AgeOutOfBoundsException(String message) { super(message); } }