Java_ Common class API (2)
Still dazzling 2021-06-04 10:36:55

JDK7 Date time class of

Date class

Date Class represents time , Time can be accurate to milliseconds . Create a Date object , In fact, it means that the time is right like .

1 Date date1=new Date(); // Current system time 
2
3 Date date2=new Date(0L); //1970 year 1 month 1 Japan 8 spot 0 when 0 branch ( China )
4
5 Date date3=new Date(1000L*60*60*24); //1970 year 1 month 2 Japan 8 spot 0 when 0 branch ( China )

Get and set time

1 Date date=new Date(); // Current system time
2 // Set the time to 
3 date.setTime(1000L*60*60*24); //1970 year 1 month 2 Japan 8 spot 0 when 0 branch ( China )
4
5 // Acquisition time 
6 long time=date.getTime(); //1000L*60*60*24
7 System.out.println(time); // Millisecond value 

 

SimpleDateFormat class

SimpleDateFormat Class can format and parse the date .

 1 SimpleDateFormat When formatting or interpreting dates , Some specific symbols need to be identified
 2  yyyy: year 1999 year
 3  MM: The month of the year 8 month
 4  dd: The day of the month 28 Japan
 5  HH: Hours in the day 16 when
 6  mm: The minute of the hour 20 branch
 7  ss: Seconds in minutes 18 second
 8  SS: millisecond
 9
10  format :Date Object to string
11
12  analysis : String conversion to Date object
13
14 // Before formatting and parsing dates , You must use the above symbols to create SimpleDateFormat object , To specify the format of the date or time 
15 SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd Japan HH when mm branch ss second ");

Here's the code for formatting and parsing

1 SimpleDateFormat sdf=new SimpleDateFormat("yyyy year MM month dd Japan HH when mm branch ss second ");
2
3 //1. Date formatting :Date object -->String
4 String str=sdf.format(new Date()); // Format the current time as a string
5
6 //2. Date resolution :String --> Date object 
7 Date date=sdf.prase("1992 year 08 month 09 Japan 16 when 24 branch 18 second "); 

practice : Enter a birthday on the keyboard ( Format :yyyy-MM-dd), Calculate the current age ?

 1 // Keyboard input string birthday 
 2 Scanner sc=new Scanner(System.in);
 3 System.out.println(" Please enter your birthday ( Format :yyyy-MM-dd):");
 4 String birthday=sc.next();
 5
 6 // Put the birthday string , Convert to Date
 7 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
 8 Date date1=sdf.prase(birthday); // On my birthday Date object 
 9 long time1=date1.getTime(); // The number of milliseconds on birthday
10
11 // Get the millisecond value of the current time 
12 long time2=System.currentTimeMills(); // The millisecond value of the current time
13
14 // Calculate the time difference 
15 long age=(time2-time1)/1000/60/60/24/365;
16 System.out.println(" Age is :"+age);

 

JDK8 New date class

LocalDateTime Get objects

LocalDateTime class It can express time ( year 、 month 、 Japan 、 when 、 branch 、 second )

1 public static LocalDateTime now()
2  Get the current system time LocalDateTime object
3 public static LocalDateTime of(int y,int m,int d,int h,int m,int s)
4 Get the specified time of LocalDateTime object 

Code demonstration

1 // Get the current time object 
2 LocalDateTime ldt1 = LocalDateTime.now();
3
4 // Gets the specified time object ,2011 year 11 month 11 Japan 10 spot 10 branch 10 second 
5 LocalDateTime ldt2 = LocalDateTime.of(2011,11,11,10,10,10);

 

LocalDateTime How to get

 1 public int getYear()
 2  Year of acquisition
 3 public int getMonthValue()
 4  Get the month
 5 public int getDayOfMonth()
 6  Get the days of the month
 7 public int getDayOfYear()
 8  Get the day of the year
 9 public DayOfWeek getDayOfWeek()
10  Get the day of the week
11 public int getHour()
12  For hours
13 public int getMinute()
14  Get minutes
15 public int getSecond()
16 Get seconds 

 

LocalDateTime The transformation method of

 1  Differences among the three
 2  LocalDateTime: Include year 、 month 、 Japan 、 when 、 branch 、 second
 3  LocalDate: Include year 、 month 、 Japan
 4  LocalTime: Inclusion time 、 branch 、 second
 5
 6  Can pass LocalDateTime Convert to LocalDate and LocalTime
 7 public LocalDate toLocalDate()
 8  hold LocalDateTime Convert to LocalDate
 9 public LocalTime toLocalTime()
10 hold LocalDateTime Convert to LocalTime

 

LocalDateTime Format and parse

1 public String format(DateTimeFormatter formatter)
2  format : hold LocalDateTime Convert to String
3 static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter)
4 analysis : Convert string to LocalDateTime object 

Date format code demo

1 // Get the... Of the current time LocalDateTime object 
2 LocalDateTime localDateTime = LocalDateTime.now();
3
4 // Create a date formatter 
5 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
6
7 // format 
8 String str=localDateTime.format(formatter);
9 System.out.println(str);

Date parsing code demonstration

1 // Create a date formatter 
2 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
3
4 // Date resolution 
5 LocalDateTime localDateTime= LocalDateTime.parse("2020-08-23 15:19:39",formatter);
6
7 //... You can use it later LocalDateTime Methods , Operate on time 

 

LocalDateTime The method of addition and subtraction

 1 public LocalDateTime plusYears(int n)
 2  Add 、 Minus years ( A positive number means increase 、 A negative number means a decrease )
 3 public LocalDateTime plusMonths(int n)
 4  Add 、 Minus month
 5 public LocalDateTime plusDays(int n)
 6  Add 、 Minus days
 7 public LocalDateTime plusHours(int n)
 8  Add 、 Minus time
 9 public LocalDateTime plusMinutes(int n)
10  Add 、 points
11 public LocalDateTime plusSeconds(int n)
12 Add 、 Minus seconds 

 

LocalDateTime How to set the time

 1 public LocalDateTime withYear(int n)
 2  Set year
 3 public LocalDateTime withMonth(int n)
 4  Set month
 5 public LocalDateTime withDay(int n)
 6  Set day
 7 public LocalDateTime withHour(int n)
 8  When setting
 9 public LocalDateTime withMinute(int n)
10  Set points
11 public LocalDateTime withSecond(int n)
12 Set seconds 

 

Time interval class

Period class

Calculate the year between two time intervals 、 month 、 Japan .

 1 // Birthday time 
 2 LocalDate localDate1 = LocalDate.of(1996, 6, 23);
 3
 4 // Today's time 
 5 LocalDate localDate2 = LocalDate.now();
 6
 7 // Get the interval object 
 8 Period period = Period.between(localDate1,localDate2);
 9
10 // Get years apart 
11 int years = period.getYears();
12 System.out.println(years);
13
14 // Get months apart 
15 long totalMonths = period.getMonths();
16 System.out.println(totalMonths);
17
18 // Get the days between 
19 int days = period.getDays();
20 System.out.println(days);

 

Duration class

Calculate the time between two time intervals 、 branch 、 second

 1 // When time 
 2 LocalDateTime localDate1 = LocalDateTime.now();
 3 // National Day 
 4 LocalDateTime localDate2 = LocalDateTime.of(2021, 10, 1,0,0,0);
 5
 6 // Get the interval object 
 7 Duration duration = Duration.between(localDate1,localDate2);
 8
 9 // Get the total number of hours between 
10 long hour = duration.toHours();
11 // Get the total number of minutes separated 
12 long minutes = duration.toMinutes();
13 // Gets the total number of seconds separated 
14 long seconds = duration.toSeconds();
15 // The total number of milliseconds and seconds between 
16 long millis = duration.toMillis();
17
18 System.out.println("-----------");
19
20 // Get the days apart 
21 long day = duration.toDaysPart();
22 // Get the parts separated by hours 
23 int hoursPart = duration.toHoursPart();
24 // Get the minutes apart 
25 int minutesPart = duration.toMinutesPart();
26 // Get the seconds apart 
27 int secondsPart = duration.toSecondsPart();
28 System.out.println(" It's still far from the National Day holiday this year :"+day+" God "+hoursPart+" Hours "+minutesPart+" minute "+secondsPart+" second ");

 

abnormal

The exception is actually some abnormal exception of the program during compilation and running . Java The engineers of , Encapsulate some common problems with exception classes , stay API It's listed for you in . When we use Java When you write code in language , These problems may arise , When these problems arise , You can go API In looking for , Where is the problem .

The inheritance system of exception class

1 Throwable Is the root class for all exceptions and errors
2  Error: error , Unsolvable problems .
3  Exception: abnormal , Problems that can be solved .
4  RuntimeException: Runtime exception , Problems only occur at run time
5 Not RuntimeException: Compile time exception , There was a problem compiling .

 

Exception handling

The virtual machine handles it itself

Stop the program directly , Then print the exception information on the console

try...catch Handle by hand

1 try{
2 // Check for exceptions in the code 
3 }catch( Exception class e){
4 // If try There's something unusual in , Will be catch Capture to 
5 }
6
7 benefits : After processing, the code can continue to execute 

throws Declaration exception

throws Used in methods , To declare a method, it may have an exception

1 // If a method is followed by throws Declaration exception , Then you need to handle exceptions when calling methods .
2 public static void method(String str) throws ParseException {
3 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
4 Date date = sdf.parse(str);
5  System.out.println(date);
6 }

 

Throwable Methods

1 public String getMessage()
2  Get exception information
3 public String toString()
4 Returns the exception class name + Abnormal information
5 public void printStackTrace()
6 Print detailed exception information 

 

throw Create an exception

If you write API People who , When writing methods , Consider the method's caller passing illegal parameters . You have to check the validity of these parameters first , If it doesn't go through , Tell the caller an exception .

 1 public static void main(String[] args) {
 2 sale(7);
 3 }
 4
 5 public static void sale(int money){
 6 if(money==5||money==10){
 7 System.out.println(" Money is real , You can buy things normally ");
 8 }else{
 9 throw new RuntimeException(" The money is fake , I called the police , Waiting for the !!!");
10  }
11 }

 

Custom exception

If you're writing a method ,API Exception classes provided in , It's not enough to explain the procedure . You can define an exception class yourself

1  Steps to customize exception classes :
2 1. Write a class inheritance Exception perhaps RuntimeException
3 2. Automatically generate two construction methods
4
5 Be careful : Custom exception , Name must be known by name ( It's better to be able to use the name of the exception class , To illustrate the problem )

 

Please bring the original link to reprint ,thank
Similar articles

2021-08-09

2021-08-09