Variable string class and date related class
Variable string class------------------------------
public final class StringBuffer
extends Object
implements Serializable, Comparable<StringBuffer>, CharSequence
//Serializable, serializable interface
//Comparable < StringBuffer >, comparator interface
//CharSequence, character sequence interface
public final class StringBuilder
extends Object
implements Serializable, Comparable<StringBuilder>, CharSequence
//Serializable, serializable interface
//Comparable < StringBuilder >, comparator interface
//CharSequence, character sequence interface
Since the String content described by the String class is a constant, it cannot be changed
When a large number of similar strings need to be described in Java code, they can only be applied and stored separately, which will cause a waste of memory space
To solve the above problems, you can use Java Lang.stringbuilder class and Java Lang. StringBuffer class to describe strings that can be changed by character sequences
For example: "ab", this "ab" is the of these two classes. It is a string that can be adjusted and the content can be changed
The StringBuffer class is from jdk1 0 began to exist. It belongs to thread safe class (it cannot be executed until the execution is completed, so it is safe). Therefore, the efficiency is relatively low (you must wait for the execution to be completed)
The StringBuilder class is from jdk1 5 began to exist, belonging to non thread safe classes (all executed together, unsafe), with high efficiency (no waiting)
StringBuffer is basically as like as two peas in StringBuilder.
But StringBuilder replaces StringBuffer, so let's talk about the StringBuilder class here
Common construction methods of StringBuilder class------------------------------
StringBuilder(),The object is constructed without parameters, with a capacity of 16(Apply for a memory space that can hold 16 characters)
StringBuilder(int capacity),The object is constructed according to the capacity specified by the parameter, and the capacity specifies the size for the parameter
StringBuilder(String str),Construct the object according to the string specified by the parameter. The capacity is: 16+String length
Common member methods of StringBuilder class------------------------------
int capacity(),Used to return the capacity of the calling object
int length(),Used to return the length of a string, that is, the number of characters
StringBuilder insert(int offset, String str),Insert a string and return a reference to the calling object, which is itself
StringBuilder append(String str),Append string,Append at the end
StringBuilder deleteCharAt(int index),Subscript the current string to index Single character deletion of position
StringBuilder delete(int start,int end),Delete string, delete start reach end String between, including start,barring end
StringBuilder replace(int start,int end,String str),Replace string
StringBuilder reverse(),String inversion
//The search method of variable String is similar to that in String class, such as charAt method of String class
//Of course, other methods of String are similar to those of variable String and many other classes
//Some classes implement almost the same interfaces, so some methods are similar
void setCharAt(int index,char ch),The character at the specified index is set to ch
Note: if passed as a parameter, the internal String of the method will not change its value, and StringBuffer and StringBuilder will change its value
Design of return value------------------------------
The return values of many methods of StringBuilder are of type StringBuilder
The return statements of these methods are: return this
It can be seen that these methods return the reference of the object after changing the character sequence encapsulated by StringBuilder
The purpose of this design is that it can be called continuously
package com.lagou.task13;
import java.util.Arrays;
public class StringBuilderTest {
public static void main(String[] args) {
// 1. Use parameterless method to construct StringBuilder type objects and print capacity and length
//StringBuilder(), using parameterless method to construct objects, with a capacity of 16 (apply for a memory space, which can hold 16 characters)
StringBuilder sb1 = new StringBuilder();
System.out.println("sb1 = " + sb1); // Automatically calling the toString method does nothing
//int capacity(), used to return the capacity of the calling object
System.out.println("The capacity is:" + sb1.capacity()); // 16
//int length(), used to return the length of the string, that is, the number of characters
System.out.println("The length is:" + sb1.length()); // 0
System.out.println("-----------------------------------------------------------");
// 2. Use the capacity specified by the parameter to construct the object and print the capacity and length
//StringBuilder(int capacity) constructs objects according to the capacity specified in the parameter, and the capacity specifies the size for the parameter
StringBuilder sb2 = new StringBuilder(20);
System.out.println("sb2 = " + sb2); // Automatically calling the toString method does nothing
System.out.println("The capacity is:" + sb2.capacity()); // 20
System.out.println("The length is:" + sb2.length()); // 0
System.out.println("-----------------------------------------------------------");
// 3. Construct the object according to the string content specified by the parameter and print the capacity and length
//StringBuilder(String str) constructs objects according to the string specified by the parameter, with a capacity of 16 + string length
StringBuilder sb3 = new StringBuilder("hello");
System.out.println("sb3 = " + sb3); // Automatically call toString method hello
System.out.println("The capacity is:" + sb3.capacity()); // 16 + 5 = 21
System.out.println("The length is:" + sb3.length()); // 5
System.out.println("-----------------------------------------------------------");
String str1 = new String("hello");
String str2 = str1.toUpperCase();
System.out.println("str2 = " + str2); // HELLO
System.out.println("str1 = " + str1); // The hello string itself is a constant and will not change
// 4. Insert and append string contents to the string
// Insert the string content "abcd" at the position with subscript 0, that is, insert the string content at the beginning
//StringBuilder insert(int offset, String str) inserts a string and returns a reference to the calling object, which is itself
StringBuilder sb4 = sb3.insert(0, "abcd");
System.out.println("sb4 = " + sb4); // abcdhello
//Returns the reference of the calling object itself, that is, the return value and the calling object are the same string
System.out.println("sb3 = " + sb3); // abcdhello
// Insert the string "1234" into the middle position
sb3.insert(4, "1234");
System.out.println("sb3 = " + sb3); // abcd1234hello
// Insert the string "ABCD" at the end
sb3.insert(sb3.length(), "ABCD");
System.out.println("sb3 = " + sb3); // abcd1234helloABCD
//Insertion is extrusion. 0 is the first place, in is the selected subscript, and in the end is the end
System.out.println("-----------------------------------------------------------");
// Append string content to end position
//StringBuilder append(String str), append string
sb3.append("world");
System.out.println("sb3 = " + sb3); // abcd1234helloABCDworld capacity is greater than 21
// When the length of the string exceeds the initial capacity of the string object, the string object will be automatically expanded
// The default capacity expansion algorithm is: original capacity * 2 + 2 = > 21 * 2 + 2 = > 44
int[] a = new int[]{1,2,3};
int[] b = Arrays.copyOf(a,6);
//Arrays. Copyof (array, number of copies). This array has many types
//Returns the copied array of the specified array. Expand, add 0, reduce and eliminate
int[] c = Arrays.copyOf(a,2);
int[] d = Arrays.copyOf(a,3);
System.out.println(Arrays.toString(b)); //[1, 2, 3, 0, 0, 0]
System.out.println(Arrays.toString(c)); //[1, 2]
System.out.println(Arrays.toString(d)); //[1, 2, 3]
// The bottom layer uses byte array to store all character contents.
// ctrl+alt + left and right arrow keys indicate that you return to the up / down position
//Role in looking at the source code
System.out.println("The capacity is:" + sb3.capacity()); // 44
System.out.println("The length is:" + sb3.length()); // 22
System.out.println("-----------------------------------------------------------");
// 5. Delete the characters and strings in the string
// Indicates the deletion of a single character with a subscript of 8
//StringBuilder deleteCharAt(int index) deletes a single character in the current string whose subscript is the index position
sb3.deleteCharAt(8); //The return value of the method may not be obtained
System.out.println("sb3 = " + sb3); // abcd1234elloABCDworld
// Use the for loop to delete multiple characters
for (int i = 8; i < 12; i++) {
// The results show that after deleting a character, skip a character and continue to delete
//sb3.deleteCharAt(i);
// Because every time a character is deleted, the following characters will be filled forward, because the subscript will change
// Therefore, characters with subscript 8 are always deleted
sb3.deleteCharAt(8);
}
System.out.println("The deleted string is:" + sb3); // abcd1234ABCDworld
System.out.println("-----------------------------------------------------------");
// Delete the starting string abcd, containing 0 but not 4
//StringBuilder delete(int start, int end) to delete strings
sb3.delete(0, 4);
System.out.println("sb3 = " + sb3); // 1234ABCDworld
// Delete intermediate string
sb3.delete(4, 8);
System.out.println("sb3 = " + sb3); // 1234world
// Delete end string
sb3.delete(4, sb3.length());
System.out.println("sb3 = " + sb3); // 1234
System.out.println("-----------------------------------------------------------");
// 6. Realize the modification, search and inversion of string content
// Indicates that the character with subscript 0 is modified to 'a'
sb3.setCharAt(0, 'a');
System.out.println("The content after modifying a single character is:" + sb3); // a234
// Modify "234" to "bcd"
//StringBuilder replace(int start, int end, String str) to replace the string
sb3.replace(1, 4, "bcd");
System.out.println("The result of modifying the string is:" + sb3); // abcd
// Realize the function of searching
int pos = sb3.indexOf("b");
System.out.println("The search results from front to back are:" + pos); // 1
pos = sb3.lastIndexOf("b");
System.out.println("The results of the back-to-front search are:" + pos); // 1
// Realize the inversion function of string
//StringBuilder reverse(), string inversion
sb3.reverse();
System.out.println("The result of inversion is:" + sb3); // dcba
System.out.println("-----------------------------------------------------------");
// 7. Written examination site
// Test point 1: since the object of StringBuilder class itself can be modified, why does the member method still have a return value?
// Parsing: for continuous calls
//sb3.reverse().append("1").append("2").insert(0, "3").delete(0, 1).reverse();
// Test point 2: how to realize the conversion between StringBuilder type and String type?
//String str3 = sb3.toString();
//StringBuilder sb5 = new StringBuilder(str3);
// Test point 3: who is the most efficient among String, StringBuilder and StringBuffer? How is the arrangement?
// String < StringBuffer < StringBuilder
//The reason why String < StringBuffer is that String needs a new object to apply for memory every time it moves
//There is also an object in the constant pool
//StringBuffer can adjust the original string itself
}
}
Overview of the System class------------------------------
public final class System
extends Object
Java. Some useful class fields and methods are provided in the lang. system class
//System.out standard output
//System.in standard input
//arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
//src array to copy
//srcPos the starting index of the array to copy
//dest target array
//Start index of destPos target array
//length number of to copy
//As shown below
//Indicates that the three elements in array arr with subscripts starting from 1 are copied to the position in array brr with subscripts starting from 0
System.arraycopy(arr,1,brr,0,3);
Common methods------------------------------
static long currentTimeMillis(),Returns the time difference in milliseconds between the current time and 0:0:0:0 on January 1, 1970
package com.lagou.task13;
public class SystemTest {
public static void main(String[] args) {
// 1. Obtain the number of milliseconds from the current system time to 0:0:0 on January 1, 1970
//static long currentTimeMillis(), returns the time difference in milliseconds between the current time and 0:0:0 on January 1, 1970
long msec = System.currentTimeMillis();
System.out.println("The current system time has passed since 0:00:00 on January 1, 1970" + msec + "Milliseconds!");
// It is usually used to test the execution efficiency of a piece of code
}
}
Overview of the Date class------------------------------
public class Date
extends Object
implements Serializable, Cloneable, Comparable<Date>
//Serializable, serializable interface
//Clonable, tag interface
//Comparable < date >, comparator interface
java. util. The date class is mainly used to describe a specific moment, that is, month, day, hour, minute and second, which can be accurate to milliseconds
Common methods------------------------------
Date(),The object is constructed in a parameterless manner, that is, the current system time
Date(long date),Construct the object according to the number of milliseconds specified by the parameter. The parameter is the number of milliseconds from 0:0:0 on January 1, 1970
long getTime(),Gets the number of milliseconds from the calling object to 0:0:0 on January 1, 1970
void setTime(long time),Set the calling object as the distance from the base time time Time point in milliseconds
//Benchmark time: 0:00:00, 1 January 1970
package com.lagou.task13;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
// 1. Construct the Date object in parameterless mode and print it
//Date(), the object is constructed in a parameterless way, that is, the current system time
Date d1 = new Date();
System.out.println("d1 = " + d1); // Get current system time
System.out.println("------------------------------------");
// 2. Use the number of milliseconds specified in the parameter to construct the Date object and print the East 8 area with 1 second = 1000 milliseconds
//Date(long date), construct the object according to the number of milliseconds specified by the parameter. The parameter is the number of milliseconds from 0:0:0 on January 1, 1970
Date d2 = new Date(1000);
System.out.println("d2 = " + d2); // 1970 1 1 8 0 1
// It was originally 1970 1 0 0 1, but because it was the East eighth District, it was 1970 1 8 0 1, with different time zones
//Eight hours short
System.out.println("------------------------------------");
// 3. Get the number of milliseconds from the calling object to 0:0:0 on January 1, 1970
//long getTime(), gets the number of milliseconds from the calling object to 0:0:0 on January 1, 1970
long msec = d2.getTime();
System.out.println("The number of milliseconds obtained is:" + msec); // 1000
// 4. Set the time point represented by the calling object as the number of milliseconds specified by the parameter
//void setTime(long time), set the calling object as the time point in milliseconds from the reference time time
d2.setTime(2000);
System.out.println("The modified time is:" + d2); // 1970 1 1 8 0 2
}
}
Overview of the SimpleDateFormat class------------------------------
public class SimpleDateFormat
extends DateFormat
public abstract class DateFormat
extends Format
public abstract class Format
extends Object
implements Serializable, Cloneable
//Serializable, serializable interface
//Clonable, tag interface
java. text. The simpledateformat class is mainly used to realize the conversion between date and text
Common methods------------------------------
SimpleDateFormat(),Construct objects with no parameters
SimpleDateFormat(Stringpattern),The object is constructed according to the pattern specified by the parameter. The patterns mainly include: y-year M-month d-day H-Time m-branch s-second
final String format(Datedate),Used to convert a date type to a text type
Date parse(String source),Used to convert a text type to a date type
package com.lagou.task13;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatTest {
public static void main(String[] args) throws Exception {
// 1. Obtain the current system time and print it
Date d1 = new Date();
System.out.println("d1 = " + d1);
// 2. Construct an object of type SimpleDateFormat and specify the format
//SimpleDateFormat(), constructs the object in a parameterless manner
//Simpledateformat (string pattern) constructs an object according to the pattern specified by the parameter
//The main modes are: y-year, m-month, d-Day, H-Hour, m-minute, s-second
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//These six represent the main writing methods. Of course, you can write a to indicate afternoon or others. They all have fixed expressions, such as Y directly indicates year
//That is, Y can directly replace yyyy
//Of course, some can't be written, such as p. this is the rule in the parameter constructor of SimpleDateFormat class
//Three yyy s here are OK, but it's best not to write like that
// 3. Realize the conversion from date type to text type and print
// alt+Enter can generate the return value
//final String format(Datedate), used to convert date type to text type
String format = sdf.format(d1);
System.out.println("The date after conversion is:" + format);
// 4. Realize the conversion from text type to date type and print
//Date parse(String source), used to convert text type to date type
Date parse = sdf.parse(format);
System.out.println("The result of reversing the date format is:" + parse);
}
}
Overview of the Calendar class------------------------------
public abstract class Calendar
extends Object
implements Serializable, Cloneable, Comparable<Calendar>
//Serializable, serializable interface
//Clonable, tag interface
//Comparable < calendar >, comparator interface
java.util.Calender class is mainly used to describe a specific moment and replace the outdated methods in Date class to realize globalization
This class is an abstract class and therefore cannot instantiate an object
Its specific subclass is for calendar systems in different countries, among which Gregorian calendar is the most widely used
It corresponds to the standard calendar system used by most countries / regions in the world
Common methods------------------------------
static Calendar getInstance(),For obtaining Calendar Reference to type
void set(int year, int month, int date, int hourOfDay, intminute, int second),Used to set the information of month, day, hour, minute and second
Date getTime(),Used to Calendar Type conversion to Date type
void set(int field, int value),Sets the value of the specified field
void add(int field, int amount),Adds a value to the specified field
//field fields are constants, corresponding to specific values, such as year, month, day, hour, minute, second, etc
//amount can be negative, that is, reduce the value, which will affect other values
//Of course, int type can be negative, but some parameters are limited
package com.lagou.task13;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CalendarTest {
public static void main(String[] args) {
// 1. Use outdated methods to construct objects according to the specified time minutes of month, day and year
Date d1 = new Date(2008-1900, 8-1, 8, 20, 8, 8);
//Here, 1900 must be subtracted from the year and 1 must be subtracted from the month. In the source code, 1900 is added to the year, and the month subscript range is 0-11, so 8 represents 9
// 2. Format and print date objects
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = sdf.format(d1);
System.out.println("The obtained time is:" + format); // 2008 8 8 20 8 8
System.out.println("-----------------------------------------------------");
// 2. Use the substitution method to construct the object according to the specified month, year, day, hour, minute and second
// 2.1 get the reference of Calendar type
// Test point: since Calendar is an abstract class and cannot create an object, why can the following method obtain the reference of Calendar type?
// Analysis: it can be seen from the source code that the returned object is not an object of Calendar type
// Instead, objects such as Gregorian Calendar, a subclass of the Calendar class, form polymorphisms
// The third application occasion of polymorphism
//static Calendar getInstance(), used to get the reference of Calendar type
Calendar instance = Calendar.getInstance();
// 2.2 set the specified year, month, day, hour, minute and second information
//void set(int year, int month, int date, int hourOfDay, intminute, int second)
// Used to set the information of month, day, hour, minute and second
instance.set(2008, 8-1, 8, 20, 8, 8);
//In the source code, the month subscript range is 0-11, so 8 means 9
//Although the code of Date is simple, it does not adapt to globalization. Although the Calendar above is a little complex, it adapts to globalization, that is, it has something to give up
//Among them, the year, month, day, hour, minute and second settings of Date are outdated. Maybe they will be removed on that day, so it's not good
// 2.3 objects converted to Date type
//Date getTime(), used to convert Calendar type to date type
Date d2 = instance.getTime();
String format1 = sdf.format(d2);
System.out.println("The obtained time is:" + format1); // 2008 8 8 20 8 8
System.out.println("-----------------------------------------------------");
// 3. Set and increase the specified value to the specified field
//void set(int field, int value) to set the value of the specified field
instance.set(Calendar.YEAR, 2018);
// Convert to Date type and print in the specified format
Date d3 = instance.getTime();
System.out.println("After setting the year, the result is:" + sdf.format(d3)); // 2018 8 8 20 8 8
//void add(int field, int amount) to add a value to the specified field
instance.add(Calendar.MONTH, 2);
Date d4 = instance.getTime();
System.out.println("The result after adding months is:" + sdf.format(d4)); // 2018 10 8 20 8 8
}
}
Polymorphic usage------------------------------
//Three applications of polymorphism
//Polymorphism is formed through parameter passing of the method
public static void draw(Shape s){
s.show();
}
draw(new Rect(1, 2, 3, 4));
//Use polymorphic syntax formats directly in the method body
Account acc = new FixedAccount();
//Polymorphism is formed by the return value type of the method
Calender getInstance(){
return new GregorianCalendar(zone, aLocale);
}
Origin of Java 8 date class------------------------------
JDK 1.0 includes a Java util. Date class, but most of its methods have been deprecated since JDK 1.1 introduced the Calendar class
Calendar is not much better than Date
The problem they face is that the year in the Date class starts from 1900 and the month starts from 0. Formatting is only useful for the Date class, but not for the Calendar class
Non thread safety, etc
Overview of Java 8 date classes------------------------------
//Java 8 further strengthens the processing of date and time by publishing a new date time API
//java.time package: this package is the base package of the date / time API
//java.time.chrono package: this package provides access to different calendar systems
//java.time.format package: this package can format and parse date time objects
//java. time. Temporary package: this package contains the underlying framework and extension features
//java.time.zone package: this package supports classes with different time zones and related rules
Overview of the LocalDate class------------------------------
public final class LocalDate
extends Object
implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable
//Serializable, serializable interface
//ChronoLocalDate, chronological comparator interface
//Temporal, an interface that defines read-write access to temporal objects such as date, time, offset, or some combination thereof
//TemporalAdjuster, time regulator interface
java. time. The localdate class is mainly used to describe date information in year month day format. This class does not represent time and time zone information
Common methods------------------------------
static LocalDate now(),Gets the current date from the system clock in the default time zone
Overview of the LocalTime class------------------------------
public final class LocalTime
extends Object
implements Temporal, TemporalAdjuster, Comparable<LocalTime>, Serializable
//Serializable, serializable interface
//Comparable < Localtime >, comparator interface
//Temporal, an interface that defines read-write access to temporal objects such as date, time, offset, or some combination thereof
//TemporalAdjuster, time regulator interface
java. time. The Localtime class is mainly used to describe time information, which can describe hours, minutes, seconds and nanoseconds
Common methods------------------------------
static LocalTime now(),Gets the current time from the system time in the default time zone
static LocalTime now(ZoneId zone),Gets the current time in the specified time zone
Overview of the LocalDateTime class------------------------------
public final class LocalDateTime
extends Object
implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable
//Serializable, serializable interface
//Comparable < localdate >, comparator interface
//Temporal, an interface that defines read-write access to temporal objects such as date, time, offset, or some combination thereof
//TemporalAdjuster, time regulator interface
java. time. The localdatetime class is mainly used to describe the date and time without time zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30
Common methods------------------------------
static LocalDateTime now(),Gets the current date and time from the system time in the default time zone
static LocalDateTime of(int year, int month, intdayOfMonth, int hour, int minute, int second)
Set the date and time according to the year, day, hour, minute and second information specified in the parameter
int getYear(),Gets the value of the year field
int getMonthValue(),Gets the month field between 1 and 12
int getDayOfMonth(),Get date field
int getHour(),Get hours
int getMinute(),Get minutes
int getSecond(),Get seconds
LocalDateTime withYear(int year),Set the year specified for the parameter
LocalDateTime withMonth(int month),Set the month specified for the parameter
LocalDateTime withDayOfMonth(int dayOfMonth),Sets the day specified for the parameter
LocalDateTime withHour(int hour),When set to the value specified by the parameter
LocalDateTime withMinute(int minute),Set the minute specified for the parameter
LocalDateTime withSecond(int second),Set the second specified for the parameter
LocalDateTime plusYears(long years),Add the year specified by the parameter
LocalDateTime plusMonths(long months),Add the month specified by the parameter
LocalDateTime plusDays(long days),Add the day specified by the parameter
LocalDateTime plusHours(long hours),When the value specified by the parameter is added
LocalDateTime plusMinutes(long minutes),Add the score specified by the parameter
LocalDateTime plusSeconds(long seconds),Plus the second specified by the parameter
LocalDateTime minusYears(long years),Subtract the year specified by the parameter
LocalDateTime minusMonths(long months),Subtract the month specified by the parameter
LocalDateTime minusDays(long days),Subtract the day specified by the parameter
LocalDateTime minusHours(long hours),When subtracting the value specified by the parameter
LocalDateTime minusMinutes(long minutes),Subtract the score specified by the parameter
LocalDateTime minusSeconds(long seconds),Subtracts the second specified by the parameter
package com.lagou.task13;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class LocalDateTimeTest {
public static void main(String[] args) {
// 1. Obtain the current date information and print it
//static LocalDate now(), get the current date from the system clock in the default time zone
LocalDate now = LocalDate.now();
System.out.println("The current date obtained is:" + now);
// 2. Obtain the current time information and print it
//static LocalTime now(), get the current time from the system time in the default time zone
// Only get the time, not the date, and nanoseconds. There are 9 digits after the decimal point of seconds
LocalTime now1 = LocalTime.now();
System.out.println("The current time obtained is:" + now1);
// 3. Obtain and print the current date and time information, which can be used at most
//static LocalDateTime now(), get the current date and time from the system time in the default time zone
LocalDateTime now2 = LocalDateTime.now();
System.out.println("The current date and time obtained is:" + now2);
System.out.println("-------------------------------------------------------");
// 4. Use the year, day, hour, minute and second information specified by the parameter to obtain the object and print it
// Use ctrl+F12 to find the specified method
/*static LocalDateTime of(int year, int month,
intdayOfMonth, int hour, int minute, int second)
*/
//Set the date and time according to the year, day, hour, minute and second information specified in the parameter
LocalDateTime of = LocalDateTime.of(2008, 8, 8, 20, 8, 8);
System.out.println("The specified date and time is:" + of); // Automatically call toString method
//int getYear(), get the value of the year field
//int getMonthValue(), get the month field between 1 and 12
//int getDayOfMonth(), get date field
//int getHour(), get hours
//int getMinute(), get minutes
//int getSecond(), get seconds
System.out.println("The year obtained is:" + of.getYear()); // 2008
System.out.println("The months obtained are:" + of.getMonthValue()); // 8
System.out.println("The date obtained is:" + of.getDayOfMonth()); // 8
System.out.println("The obtained is:" + of.getHour()); // 20
System.out.println("The scores obtained are:" + of.getMinute()); // 8
System.out.println("The seconds obtained are:" + of.getSecond()); // 8
System.out.println("-------------------------------------------------------");
//LocalDateTime withYear(int year), set to the year specified by the parameter
//LocalDateTime withMonth(int month), set to the month specified by the parameter
//LocalDateTime withDayOfMonth(int dayOfMonth), set to the day specified by the parameter
//LocalDateTime withHour(int hour), set to the time specified by the parameter
//LocalDateTime withMinute(int minute), set to the minute specified by the parameter
//LocalDateTime withSecond(int second), set to the second specified by the parameter
// 5. Realize feature setting and printing
// Similar to the String type, the data content of the calling object itself will not change
// The return value is equivalent to creating a new object, which proves immutability
LocalDateTime localDateTime = of.withYear(2012);
System.out.println("localDateTime = " + localDateTime); // 2012-08-08T20:08:08
System.out.println("of = " + of); // 2008-08-08T20:08:08
LocalDateTime localDateTime1 = localDateTime.withMonth(12);
System.out.println("localDateTime1 = " + localDateTime1); // 2012 12 8 20 8 8
System.out.println("-------------------------------------------------------");
//LocalDateTime plusYears(long years), plus the year specified by the parameter
//LocalDateTime plusMonths(long months), plus the month specified by the parameter
//LocalDateTime plusDays(long days), plus the day specified by the parameter
//LocalDateTime plusHours(long hours), plus the time specified by the parameter
//LocalDateTime plusMinutes(long minutes), plus the score specified in the parameter
//LocalDateTime plusSeconds(long seconds), plus the second specified by the parameter
// 6. Add and print features
LocalDateTime localDateTime2 = localDateTime1.plusDays(2);
System.out.println("localDateTime2 = " + localDateTime2); // 2012 12 10 20 8 8
System.out.println("localDateTime1 = " + localDateTime1); // 2012 12 8 20 8 8
LocalDateTime localDateTime3 = localDateTime2.plusHours(3);
System.out.println("localDateTime3 = " + localDateTime3); // 2012 12 10 23 8 8
System.out.println("-------------------------------------------------------");
//LocalDateTime minusYears(long years), minus the year specified by the parameter
//LocalDateTime minusMonths(long months), minus the month specified by the parameter
//LocalDateTime minusDays(long days), minus the day specified in the parameter
//Localdatetime minuhours (long hours), minus the time specified by the parameter
//LocalDateTime minusMinutes(long minutes), minus the score specified in the parameter
//LocalDateTime minusSeconds(long seconds), minus the second specified by the parameter
// 7. Reduce features and print
LocalDateTime localDateTime4 = localDateTime3.minusMinutes(1);
System.out.println("localDateTime4 = " + localDateTime4); // 2012 12 10 23 7 8
System.out.println("localDateTime3 = " + localDateTime3); // 2012 12 10 23 8 8
LocalDateTime localDateTime5 = localDateTime4.minusSeconds(3);
System.out.println("localDateTime5 = " + localDateTime5); // 2012 12 10 23 7 5
}
}
Overview of the Instant class------------------------------
public final class Instant
extends Object
implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable
//Serializable, serializable interface
//Comparable < instant >, comparator interface
//Temporal, an interface that defines read-write access to temporal objects such as date, time, offset, or some combination thereof
//TemporalAdjuster, time regulator interface
java. time. The instant class is mainly used to describe the instantaneous point in time information
Common methods------------------------------
static Instant now(),Gets the current time from the system clock
OffsetDateTime atOffset(ZoneOffset offset),Combine this moment with the offset to create an offset date time
static Instant ofEpochMilli(long epochMilli)
The object is constructed according to the number of milliseconds specified by the parameter. The parameter is the number of milliseconds from 0:0:0 on January 1, 1970
long toEpochMilli(),Gets the number of milliseconds from 0:0:0 on January 1, 1970
package com.lagou.task13;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class InstantTest {
public static void main(String[] args) {
// 1. Use the Instant class to obtain the current system time, which is not the default time zone of the current system. The difference between the original meridian and the East eight areas is 8 hours
//static Instant now(), get the current time from the system clock
Instant now = Instant.now();
System.out.println("The current time obtained is:" + now);
// 2. Add the 8 hours difference in time zone
//OffsetDateTime atOffset(ZoneOffset offset) combines this moment with the offset to create an offset datetime
OffsetDateTime offsetDateTime = now.atOffset(ZoneOffset.ofHours(8));
System.out.println("The date and time after offset is:" + offsetDateTime);
System.out.println("--------------------------------------------------------");
// 3. get the millisecond number of the current calling object from the standard base time.
//Long toepochmili(), get the number of milliseconds from 0:0:0 on January 1, 1970
long g1 = now.toEpochMilli();
System.out.println("The obtained millisecond difference is:" + g1);
// 4. Construct the object according to the number of milliseconds specified by the parameter
//static Instant ofEpochMilli(long epochMilli)
//The object is constructed according to the number of milliseconds specified by the parameter. The parameter is the number of milliseconds from 0:0:0 on January 1, 1970
Instant instant = Instant.ofEpochMilli(g1);
System.out.println("The objects constructed according to the number of milliseconds specified in the parameter are:" + instant);
}
}
Overview of DateTimeFormatter class------------------------------
public final class DateTimeFormatter
extends Object
java. time. format. The datetimeformatter class is mainly used to format and parse dates
The difference between DateTimeFormatter and SimpleDateFormat: the former is safe and the latter is not safe
Common methods------------------------------
static DateTimeFormatter ofPattern(String pattern),Gets the object according to the pattern specified by the parameter String
format(TemporalAccessor temporal),Converts the date and time specified by the parameter to a string
TemporalAccessor parse(CharSequence text),Converts the string specified by the parameter to a date time
package com.lagou.task13;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
public class DateTimeFormatterTest {
public static void main(String[] args) {
// 1. Obtain the date and time of the current system and print it
LocalDateTime now = LocalDateTime.now();
System.out.println("now = " + now);
// 2. Prepare an object of DateTimeFormatter type according to the specified format
//Static datetimeformatter of pattern (String pattern), which obtains the object String according to the pattern specified by the parameter
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 3. Realize the conversion from date and time to string type and print
//Format (temporalaccessor temporary), which converts the date and time specified by the parameter into a string
String str = dateTimeFormatter.format(now); //Interface
System.out.println("The result of formatting adjustment is:" + str);
// 4. Realize the conversion from string type to date time type and print
//TemporalAccessor parse(CharSequence text) to convert the string specified by the parameter into date and time
TemporalAccessor parse = dateTimeFormatter.parse(str);
System.out.println("The result of turning back is:" + parse);
}
}