1. Time and date
1.1 Date class
-
Time origin in computer
January 1, 1970 00:00:00
-
Time conversion unit
1 second = 1000 milliseconds
-
Overview of Date class
Date represents a specific time, accurate to milliseconds
-
Date class constructor
Method name explain public Date() Allocate a Date object and initialize it so that it represents the time it is allocated, accurate to milliseconds public Date(long date) Allocates a Date object and initializes it to represent the specified number of milliseconds from the standard base time -
Sample code
public class DateDemo01 { public static void main(String[] args) { //public Date(): allocate a Date object and initialize it so that it represents the time it is allocated, accurate to milliseconds Date d1 = new Date(); //d1 is the current computer time System.out.println(d1); //public Date(long date): allocate a Date object and initialize it to represent the specified number of milliseconds from the standard base time long date = 1000*60*60; Date d2 = new Date(date); System.out.println(d2); } }
1.2 common methods of date class
-
common method
Method name explain public long getTime() Gets the millisecond value of the date object from 00:00:00, January 1, 1970 to the present public void setTime(long time) Set the time and give the value of milliseconds -
Sample code
public class DateDemo02 { public static void main(String[] args) { //Create date object Date d = new Date(); //public long getTime(): gets the millisecond value of the date object from 00:00:00 on January 1, 1970 to the present // System.out.println(d.getTime()); // System.out.println(d.getTime() * 1.0 / 1000 / 60 / 60 / 24 / 365 + "year"); //public void setTime(long time): sets the time. The value given is milliseconds // long time = 1000*60*60; long time = System.currentTimeMillis(); d.setTime(time); System.out.println(d); } }
1.3 SimpleDateFormat class
-
SimpleDateFormat class overview
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale sensitive manner.
We focus on date formatting and parsing
-
SimpleDateFormat class constructor
Method name explain public SimpleDateFormat() Construct a SimpleDateFormat, using the default mode and date format public SimpleDateFormat(String pattern) Construct a SimpleDateFormat using the given pattern and the default date format -
Common methods of the SimpleDateFormat class
-
Format (from Date to String)
-
public final String format(Date date): formats the date into a date / time string
-
-
Parsing (from String to Date)
-
public Date parse(String source): parses text from the beginning of a given string to generate a date
-
-
-
Sample code
public class SimpleDateFormatDemo { public static void main(String[] args) throws ParseException { //Format: from Date to String Date d = new Date(); // SimpleDateFormat sdf = new SimpleDateFormat(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss"); String s = sdf.format(d); System.out.println(s); System.out.println("--------"); //From String to Date String ss = "2048-08-09 11:11:11"; //ParseException SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date dd = sdf2.parse(ss); System.out.println(dd); } }
1.4 time and date exercises
-
demand
The second kill starts at 00:00:00 on November 11, 2020 and ends at 00:10:00 on November 11, 2020. The user Xiaojia orders at 00:03:47 on November 11, 2020 and the user Xiaopi orders at 00:10:11 on November 11, 2020. Judge whether the user has successfully participated in the second kill
-
Implementation steps
-
Judge whether the order placing time is within the range from start to end
-
Change the time in string form into millisecond value
-
-
code implementation
public class DateDemo5 { public static void main(String[] args) throws ParseException { //Start time: November 11, 2020 0:0:0 //End time: 0:10:0, November 11, 2020 //Xiao Jia, November 11, 2020 0:03:47 //Xiaopi, November 11, 2020 0:10:11 //1. Just judge whether the order placing time of the two students is within the range. //2. Convert every time into milliseconds. String start = "2020 November 11, 2010 0:0:0"; String end = "2020 November 11, 2010 0:10:0"; String jia = "2020 November 11, 2010 0:03:47"; String pi = "2020 November 11, 2010 0:10:11"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss"); long startTime = sdf.parse(start).getTime(); long endTime = sdf.parse(end).getTime(); // System.out.println(startTime); // System.out.println(endTime); long jiaTime = sdf.parse(jia).getTime(); long piTime = sdf.parse(pi).getTime(); if(jiaTime >= startTime && jiaTime <= endTime){ System.out.println("Xiao Jia took part in the second kill"); }else{ System.out.println("Xiao Jia didn't participate in the second kill"); } System.out.println("------------------------"); if(piTime >= startTime && piTime <= endTime){ System.out.println("Xiao PI took part in the second kill"); }else{ System.out.println("Xiao PI didn't take part in the second kill"); } } }
2.JDK8 time and date
2.1 JDK8 new date category
-
LocalDate means date (mm / DD / yyyy)
-
LocalTime indicates the time (hour, minute and second)
-
LocalDateTime means time + date (mm / DD / yyyy, H / min / s)
2.2 LocalDateTime creation method
-
Method description
Method name explain public static LocalDateTime now() Get current system time public static LocalDateTime of (year, month, day, hour, minute, second) Initializes a LocalDateTime object with the specified year, day, hour, minute, and second -
Sample code
public class JDK8DateDemo2 { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); System.out.println(now); LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 11, 11, 11); System.out.println(localDateTime); } }
2.3 LocalDateTime obtaining method
-
Method description
Method name explain public int getYear() Acquisition year public int getMonthValue() Get month (1-12) 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 week public int getMinute() Get minutes public int getHour() Get hours -
Sample code
public class JDK8DateDemo3 { public static void main(String[] args) { LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 11, 11, 20); //public int getYear() gets the year int year = localDateTime.getYear(); System.out.println("Year for" +year); //public int getMonthValue() gets the month (1-12) int month = localDateTime.getMonthValue(); System.out.println("Month is" + month); Month month1 = localDateTime.getMonth(); // System.out.println(month1); //public int getDayOfMonth() gets the day of the month (1-31) int day = localDateTime.getDayOfMonth(); System.out.println("Dated" + day); //public int getDayOfYear() gets the day of the year (1-366) int dayOfYear = localDateTime.getDayOfYear(); System.out.println("This is the third time of the year" + dayOfYear + "day"); //public DayOfWeek getDayOfWeek() get week DayOfWeek dayOfWeek = localDateTime.getDayOfWeek(); System.out.println("Week is" + dayOfWeek); //public int getMinute() get minutes int minute = localDateTime.getMinute(); System.out.println("Minutes are" + minute); //public int getHour() get hour int hour = localDateTime.getHour(); System.out.println("Hour is" + hour); } }
2.4 LocalDateTime conversion method
Method description
Method name | explain |
---|---|
public LocalDate toLocalDate () | Convert to a LocalDate object |
public LocalTime toLocalTime () | Convert to a LocalTime object |
Sample code
public class JDK8DateDemo4 { public static void main(String[] args) { LocalDateTime ldt = LocalDateTime.of(2020, 12, 12, 8, 10, 12); //public LocalDate toLocalDate() is converted into a LocalDate object LocalDate localDate = ldt.toLocalDate(); //Reserved date System.out.println(localDate); //public LocalTime toLocalTime() is converted into a LocalTime object LocalTime localTime = ldt.toLocalTime(); //Retention hours, minutes and seconds System.out.println(localTime); } }
2.5 LocalDateTime formatting and parsing
-
Method description
Method name explain public String format (specify format) Format a LocalDateTime into a string public LocalDateTime parse (string to be parsed, parsing format) Parse a date string into a LocalDateTime object public static DateTimeFormatter ofPattern(String pattern) Gets a date formatter DateTimeFormatter object using the specified date template -
Sample code
public class JDK8DateDemo5 { public static void main(String[] args) { //method1(); //method2(); } private static void method2() { //public static LocalDateTime parse (string to be parsed, parsing format) parses a date string into a LocalDateTime object String s = "2020 November 12, 2013:14:15"; DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy year MM month dd day HH:mm:ss"); LocalDateTime parse = LocalDateTime.parse(s, pattern); System.out.println(parse); } private static void method1() { LocalDateTime ldf = LocalDateTime.of(2020, 11, 12, 13, 14, 15); System.out.println(ldf); //public String format (specify format) formats a LocalDateTime into a string DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy year MM month dd day HH:mm:ss"); String s = ldf.format(pattern); System.out.println(s); } }
2.6 methods of increasing or decreasing localdatetime
-
Method description
Method name explain public LocalDateTime plusYears (long years) Add or subtract 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 -
Sample code
/** * JDK8 Time class method for adding or subtracting time */ public class JDK8DateDemo6 { public static void main(String[] args) { //public LocalDateTime plusYears (long years) add or subtract last year LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15); //LocalDateTime newLocalDateTime = localDateTime.plusYears(1); //System.out.println(newLocalDateTime); LocalDateTime newLocalDateTime = localDateTime.plusYears(-1); System.out.println(newLocalDateTime); } }
2.7 methods of reducing or increasing localdatetime
-
Method description
Method name explain public LocalDateTime minusYears (long years) Subtract or add years public LocalDateTime minusMonths(long months) Subtract or add months public LocalDateTime minusDays(long days) Subtract or add days public LocalDateTime minusHours(long hours) When subtracting or adding public LocalDateTime minusMinutes(long minutes) Subtract or add points public LocalDateTime minusSeconds(long seconds) Subtract or add seconds public LocalDateTime minusWeeks(long weeks) Subtract or add weeks -
Sample code
/** * JDK8 Time class is a method to reduce or add time */ public class JDK8DateDemo7 { public static void main(String[] args) { //public LocalDateTime minusYears (long years) subtract or add years LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15); //LocalDateTime newLocalDateTime = localDateTime.minusYears(1); //System.out.println(newLocalDateTime); LocalDateTime newLocalDateTime = localDateTime.minusYears(-1); System.out.println(newLocalDateTime); } }
2.8 LocalDateTime modification method
-
Method description
Method name explain public LocalDateTime withYear(int year) Direct modification year public LocalDateTime withMonth(int month) Direct modification month public LocalDateTime withDayOfMonth(int dayofmonth) Direct modification date (the day of the month) public LocalDateTime withDayOfYear(int dayOfYear) Direct modification date (day of the year) public LocalDateTime withHour(int hour) Directly modify hours public LocalDateTime withMinute(int minute) Direct modification minutes public LocalDateTime withSecond(int second) Directly modify seconds -
Sample code
/** * JDK8 Time class modification time */ public class JDK8DateDemo8 { public static void main(String[] args) { //public LocalDateTime withYear(int year) LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15); // LocalDateTime newLocalDateTime = localDateTime.withYear(2048); // System.out.println(newLocalDateTime); LocalDateTime newLocalDateTime = localDateTime.withMonth(20); System.out.println(newLocalDateTime); } }
2.9 period (calculation interval: mm / DD / yy)
-
Method description
Method name explain Public static period between Calculate the interval between two "times" public int getYears() Obtain the number of years during this period public int getMonths() Gets the total number of months in this period public int getDays() Gets the number of days in this period public long toTotalMonths() Gets the total number of months in this period -
Sample code
/** * Calculate the interval between two times */ public class JDK8DateDemo9 { public static void main(String[] args) { //Public static period between calculates the interval between two "times" LocalDate localDate1 = LocalDate.of(2020, 1, 1); LocalDate localDate2 = LocalDate.of(2048, 12, 12); Period period = Period.between(localDate1, localDate2); System.out.println(period);//P28Y11M11D //public int getYears() gets the number of years in this period System.out.println(period.getYears());//28 //public int getMonths() gets the number of months in this period System.out.println(period.getMonths());//11 //public int getDays() gets the number of days in this period System.out.println(period.getDays());//11 //Public long totalmonths() gets the total number of months in this period System.out.println(period.toTotalMonths());//347 } }
2.10 duration
-
Method description
Method name explain Public static durationbetween (start time, end time) Calculate the interval between two "times" public long toSeconds() Gets the seconds for this time interval public int toMillis() Gets the milliseconds for this time interval public int toNanos() Gets the nanosecond of this time interval -
Sample code
/** * Calculate the interval between two times */ public class JDK8DateDemo10 { public static void main(String[] args) { //Public static duration between calculates the interval between two "times" LocalDateTime localDateTime1 = LocalDateTime.of(2020, 1, 1, 13, 14, 15); LocalDateTime localDateTime2 = LocalDateTime.of(2020, 1, 2, 11, 12, 13); Duration duration = Duration.between(localDateTime1, localDateTime2); System.out.println(duration);//PT21H57M58S //public long toSeconds() Gets the seconds for this time interval System.out.println(duration.toSeconds());//79078 //public int toMillis() Gets the milliseconds for this time interval System.out.println(duration.toMillis());//79078000 //public int toNanos() gets the nanoseconds of this time interval System.out.println(duration.toNanos());//79078000000000 } }
3. Abnormal
3.1 abnormality
-
Overview of exceptions
An exception is an abnormal condition in the program
-
Abnormal architecture
3.2 differences between compile time exceptions and runtime exceptions
-
Compile time exception
-
Are all Exception classes and their subclasses
-
The processing must be displayed, otherwise the program will have an error and cannot be compiled
-
-
Runtime exception
-
Are RuntimeException class and its subclasses
-
You do not need to display the handling, but you can also handle the exception as you do at compile time
-
-
Illustration
3.3 the JVM handles exceptions by default
-
If there is a problem with the program, we do not do any processing. Finally, the JVM will do the default processing. The processing method includes the following two steps:
-
The name of the exception, the cause of the error and the location of the exception are output to the console
-
Program stop
-
3.4 viewing exception information
When the console prints the exception information, it will print the exception class name, the reason for the exception and the location of the exception
When debugging a bug, we can find the location of the exception, analyze the cause, and modify the exception code according to the prompt
3.5 handling exceptions in throws mode
-
Define format
public void method() throws Exception class name { }
-
Sample code
public class ExceptionDemo { public static void main(String[] args) throws ParseException{ System.out.println("start"); // method(); method2(); System.out.println("end"); } //Compile time exception public static void method2() throws ParseException { String s = "2048-08-09"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date d = sdf.parse(s); System.out.println(d); } //Runtime exception public static void method() throws ArrayIndexOutOfBoundsException { int[] arr = {1, 2, 3}; System.out.println(arr[3]); } }
-
matters needing attention
-
The throws format follows the parentheses of the method
-
Compile time exceptions must be handled. There are two handling schemes: try Catch... Or throws. If the throw scheme is adopted, the display declaration is made on the method. Who will call this method and who will handle it in the future
-
Because runtime exceptions occur only at runtime, you can not write after the method. Exceptions at runtime are handled by the jvm by default
-
3.6 throw exception
-
format
throw new exception();
-
be careful
This format is in the method, which means that the current code throws an exception manually, and the following code does not need to be executed
-
The difference between throws and throw
throws throw Used after the method declaration, followed by the exception class name Used in the method body, followed by the exception object name Indicates a declared exception, which may occur when calling this method Indicates that the exception object is thrown manually, which is handled by the statement in the method body -
Sample code
public class ExceptionDemo8 { public static void main(String[] args) { //int [] arr = {1,2,3,4,5}; int [] arr = null; printArr(arr);//Will receive an exception //We also need to handle exceptions ourselves } private static void printArr(int[] arr) { if(arr == null){ //Does the caller know that the print was successful? //System.out.println("parameter cannot be null"); throw new NullPointerException(); //When the parameter is null //An exception object is created manually and thrown to the caller, resulting in an exception }else{ for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } } }
3.7 exception handling in try catch mode
-
Define format
try { Possible exception codes; } catch(Exception class name variable name) { Exception handling code; }
-
Execution process
-
The program starts from the code in try
-
If an exception occurs, it will jump to the corresponding catch for execution
-
After execution, the program can continue to execute
-
-
Sample code
public class ExceptionDemo01 { public static void main(String[] args) { System.out.println("start"); method(); System.out.println("end"); } public static void method() { try { int[] arr = {1, 2, 3}; System.out.println(arr[3]); System.out.println("Is it accessible here"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("The array index you accessed does not exist. Please go back and modify it to the correct index"); } } }
-
be careful
-
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
-
If there is a problem in try, will the code below try be executed?
Then jump directly to the corresponding catch statement, and the code under try will not be executed again. When all the statements in catch are executed, it means that the whole system is fully executed, and continue to execute the following code
-
If the problem is not captured, how does the program run?
So try Catch is equivalent to not writing Then I didn't deal with it myself By default, it is handed over to the virtual machine
-
How to deal with multiple exceptions that may occur at the same time?
If there are multiple exceptions, you can write multiple catch es Note: if there is a child parent relationship between multiple exceptions Then the parent class must be written below
-
3.8 Throwable member method
-
common method
Method name explain public String getMessage() Returns the detailed message string for this throwable public String toString() Returns a short description of this throw public void printStackTrace() Output the abnormal error message to the console -
Sample code
public class ExceptionDemo02 { public static void main(String[] args) { System.out.println("start"); method(); System.out.println("end"); } public static void method() { try { int[] arr = {1, 2, 3}; System.out.println(arr[3]); //new ArrayIndexOutOfBoundsException(); System.out.println("Is it accessible here"); } catch (ArrayIndexOutOfBoundsException e) { //new ArrayIndexOutOfBoundsException(); // e.printStackTrace(); //public String getMessage(): returns the detailed message string of this throwable // System.out.println(e.getMessage()); //Index 3 out of bounds for length 3 //public String toString(): returns a short description of this throw // System.out.println(e.toString()); //java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 //public void printStackTrace(): output the abnormal error information on the console e.printStackTrace(); // java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 // at com.itheima_02.ExceptionDemo02.method(ExceptionDemo02.java:18) // at com.itheima_02.ExceptionDemo02.main(ExceptionDemo02.java:11) } } }
3.9 abnormal practice
-
demand
Enter the student's name and age on the keyboard, of which the age is 18 - 25 years old. If it exceeds this range, it is abnormal data and cannot be assigned It needs to be re entered until it is correct
-
Implementation steps
-
Create student object
-
Enter the name and age on the keyboard and assign it to the student object
-
If it is illegal, enter the data again
-
-
code implementation
Student class
public class Student { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { if(age >= 18 && age <= 25){ this.age = age; }else{ //When the age is illegal, an exception occurs throw new RuntimeException("Age out of range"); } } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
Test class
public class ExceptionDemo12 { public static void main(String[] args) { // Enter the student's name and age on the keyboard, of which the age is 18 - 25 years old, // Beyond this range is abnormal data and cannot be assigned It needs to be re entered until it is correct. Student s = new Student(); Scanner sc = new Scanner(System.in); System.out.println("Please enter your name"); String name = sc.nextLine(); s.setName(name); while(true){ System.out.println("Please enter age"); String ageStr = sc.nextLine(); try { int age = Integer.parseInt(ageStr); s.setAge(age); break; } catch (NumberFormatException e) { System.out.println("Please enter an integer"); continue; } catch (AgeOutOfBoundsException e) { System.out.println(e.toString()); System.out.println("Please enter an age that matches the range"); continue; } /*if(age >= 18 && age <=25){ s.setAge(age); break; }else{ System.out.println("Please enter the age that meets the requirements "); continue; }*/ } System.out.println(s); } }
3.10 custom exception
-
Overview of custom exceptions
When the exceptions provided in Java can not meet our needs, we can customize the exceptions
-
Implementation steps
-
Define exception class
-
Write inheritance
-
Provide null parameter construction
-
Provide structure with parameters
-
-
code implementation
Exception class
public class AgeOutOfBoundsException extends RuntimeException { public AgeOutOfBoundsException() { } public AgeOutOfBoundsException(String message) { super(message); } }
Student class
public class Student { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { if(age >= 18 && age <= 25){ this.age = age; }else{ //If the exceptions provided in Java can not meet our needs, we can use custom exceptions throw new AgeOutOfBoundsException("Age out of range"); } } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
Test class
public class ExceptionDemo12 { public static void main(String[] args) { // Enter the student's name and age on the keyboard, of which the age is 18 - 25 years old, // Beyond this range is abnormal data and cannot be assigned It needs to be re entered until it is correct. Student s = new Student(); Scanner sc = new Scanner(System.in); System.out.println("Please enter your name"); String name = sc.nextLine(); s.setName(name); while(true){ System.out.println("Please enter age"); String ageStr = sc.nextLine(); try { int age = Integer.parseInt(ageStr); s.setAge(age); break; } catch (NumberFormatException e) { System.out.println("Please enter an integer"); continue; } catch (AgeOutOfBoundsException e) { System.out.println(e.toString()); System.out.println("Please enter an age that matches the range"); continue; } /*if(age >= 18 && age <=25){ s.setAge(age); break; }else{ System.out.println("Please enter the age that meets the requirements "); continue; }*/ } System.out.println(s); } }