Tip: the following is the main content of this article. The following cases can be used for reference
1, API test of date and time before jdk 8
1.SimpleDateFormat: SimpleDateFormat formats and parses the Date class
API test of date and time before jdk 8
- currentTimeMillis() in System class;
- java.util.Date and subclass Java sql. Date
- SimpleDateFormat
- Calendar
1. Two operations:
1.1 format: date - > string
1.2 parsing: the reverse process of formatting, string - > date
2. Instantiation of simpledateformat
@Test public void testSimpleDateFormat() throws ParseException { //Instantiate SimpleDateFormat: use default constructor SimpleDateFormat sdf = new SimpleDateFormat(); //Format: date -- > string Date date = new Date(); System.out.println(date); String format = sdf.format(date); System.out.println(format); //Parsing: inverse process of formatting, string -- > date String str = "19-12-18 11 a.m:43"; Date date1 = sdf.parse(str); System.out.println(date1); //*************Format and parse in the specified way: call the constructor with parameters***************** // SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //format String format1 = sdf1.format(date); System.out.println(format1);//2019-02-18 11:48:27 //Parsing: the string must conform to the format recognized by SimpleDateFormat (reflected by constructor parameters), //Otherwise, throw the exception Date date2 = sdf1.parse("2020-02-18 11:48:27"); System.out.println(date2); }
2. Practice
Exercise 1: convert the string "2020-09-08" to Java sql. Date
Exercise 2: "fishing in three days and drying nets in two days" 1990-01-01 XXXX XX fishing? Drying the net?
For example: September 8, 2020? Total days
Total days % 5 == 1,2,3 : Fishing Total days % 5 == 4,0 : Drying net Calculation of total days? Mode 1:( date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24) + 1 Mode 2: 1990-01-01 --> 2019-12-31 + 2020-01-01 -->2020-09-08
@Test public void testExer() throws ParseException { String birth = "2020-09-08"; SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf1.parse(birth); // System.out.println(date); java.sql.Date birthDate = new java.sql.Date(date.getTime()); System.out.println(birthDate); }
3. Use of calendar class (abstract class)
@Test public void testCalendar(){ //1. Instantiation //Method 1: create an object of its subclass (Gregorian calendar) //Method 2: call its static method getInstance() Calendar calendar = Calendar.getInstance(); // System.out.println(calendar.getClass()); //2. Common methods //get() int days = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(days); System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); //set() //calendar variability calendar.set(Calendar.DAY_OF_MONTH,22); days = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(days); //add() calendar.add(Calendar.DAY_OF_MONTH,-3); days = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(days); //getTime(): Calendar Class -- > date Date date = calendar.getTime(); System.out.println(date); //Settime(): date -- > Calendar Class Date date1 = new Date(); calendar.setTime(date1); days = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(days); }
2, New date and time API in JDK8
1. Background of new date time API
@Test public void testDate(){ //Offset Date date1 = new Date(2020 - 1900,9 - 1,8); System.out.println(date1);//Tue Sep 08 00:00:00 GMT+08:00 2020 }
2. New time and date API
Use of LocalDate, LocalTime and LocalDateTime
explain:
1.LocalDateTime is used more frequently than LocalDate and LocalTime
2. Similar to Calendar
@Test public void test1(){ //now(): get the current date, time and date + time LocalDate localDate = LocalDate.now(); LocalTime localTime = LocalTime.now(); LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDate); System.out.println(localTime); System.out.println(localDateTime); //of(): set the specified year, month, day, hour, minute and second. No offset LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43); System.out.println(localDateTime1); //getXxx(): get related properties System.out.println(localDateTime.getDayOfMonth()); System.out.println(localDateTime.getDayOfWeek()); System.out.println(localDateTime.getMonth()); System.out.println(localDateTime.getMonthValue()); System.out.println(localDateTime.getMinute()); //Reflect immutability //withXxx(): set related properties LocalDate localDate1 = localDate.withDayOfMonth(22); System.out.println(localDate); System.out.println(localDate1); LocalDateTime localDateTime2 = localDateTime.withHour(4); System.out.println(localDateTime); System.out.println(localDateTime2); //Immutability LocalDateTime localDateTime3 = localDateTime.plusMonths(3); System.out.println(localDateTime); System.out.println(localDateTime3); LocalDateTime localDateTime4 = localDateTime.minusDays(6); System.out.println(localDateTime); System.out.println(localDateTime4); }
3. Instantaneous: Instant
Use of Instant
Similar to Java util. Date class
@Test public void test2(){ //now(): get the standard time corresponding to the original meridian Instant instant = Instant.now(); System.out.println(instant);//2019-02-18T07:29:41.719Z //Add offset of time OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8)); System.out.println(offsetDateTime);//2019-02-18T15:32:50.611+08:00 //Toepochmili(): get the number of milliseconds since 0:0:0 (UTC) on January 1, 1970 -- > getTime() of date class long milli = instant.toEpochMilli(); System.out.println(milli); //Ofepochmili(): get the Instant instance -- > date (long millisecond) by the given number of milliseconds Instant instant1 = Instant.ofEpochMilli(1550475314878L); System.out.println(instant1); }
4. DateTimeFormatter
DateTimeFormatter: formats or parses date and time
Similar to SimpleDateFormat
@Test public void test3(){ // Method 1: predefined standard format. E.g. ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; //Format: date -- > string LocalDateTime localDateTime = LocalDateTime.now(); String str1 = formatter.format(localDateTime); System.out.println(localDateTime); System.out.println(str1);//2019-02-18T15:42:18.797 //Parsing: String -- > date TemporalAccessor parse = formatter.parse("2019-02-18T15:42:18.797"); System.out.println(parse); // Mode 2: // Localization related formats. For example: ofLocalizedDateTime() // FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT: applicable to LocalDateTime DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG); //format String str2 = formatter1.format(localDateTime); System.out.println(str2);//February 18, 2019 03:47:16 PM // Localization related formats. For example: ofLocalizedDate() // FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT: applicable to LocalDate DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM); //format String str3 = formatter2.format(LocalDate.now()); System.out.println(str3);//2019-2-18 // Key point: Method 3: custom format. For example: ofPattern("yyyy MM DD HH: mm: SS") DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); //format String str4 = formatter3.format(LocalDateTime.now()); System.out.println(str4);//2019-02-18 03:52:09 //analysis TemporalAccessor accessor = formatter3.parse("2019-02-18 03:52:09"); System.out.println(accessor); }
3, Java comparator
1, Note: under normal circumstances, objects in Java can only be compared: = = or! =. Cannot use > or <
However, in the development scenario, we need to sort multiple objects. By implication, we need to compare the size of objects.
How? Use either of the two interfaces: Comparable or Comparator
2, Comparison between the use of Comparable interface and Comparator: once the method of Comparable interface is certain, it can ensure that the object of the implementation class of Comparable interface can be compared in size at any position.
The Comparator interface is a temporary comparison.
1. Natural sorting
Example of using Comparable interface: natural sorting
1. For example, String and wrapper classes implement the Comparable interface, rewrite the compareTo(obj) method, and give a way to compare the sizes of two objects.
2. After rewriting the compareTo() method for String and wrapper classes, they are arranged from small to large
3. Rules for rewriting compareTo(obj):
If the current object this is greater than the formal parameter object obj, a positive integer is returned,
If the current object this is less than the formal parameter object obj, a negative integer is returned,
If the current object this is equal to the parameter object obj, zero is returned.
4. For custom classes, if sorting is required, we can let the custom class implement the Comparable interface and override the compareTo(obj) method.
Indicate how to sort in the compareTo(obj) method
@Test public void test1(){ String[] arr = new String[]{"AA","CC","KK","MM","GG","JJ","DD"}; // Arrays.sort(arr); System.out.println(Arrays.toString(arr)); }
Goods class:
public class Goods implements Comparable{ private String name; private double price; public Goods() { } public Goods(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Goods{" + "name='" + name + '\'' + ", price=" + price + '}'; } //Specify the way to compare the size of goods: sort according to the price from low to high, and then sort according to the product name from high to low @Override public int compareTo(Object o) { // System.out.println("**************"); if(o instanceof Goods){ Goods goods = (Goods)o; //Mode 1: if(this.price > goods.price){ return 1; }else if(this.price < goods.price){ return -1; }else{ // return 0; return -this.name.compareTo(goods.name); } //Mode 2: // return Double.compare(this.price,goods.price); } // return 0; throw new RuntimeException("The data type passed in is inconsistent!"); } }
@Test public void test2(){ Goods[] arr = new Goods[5]; arr[0] = new Goods("lenovoMouse",34); arr[1] = new Goods("dellMouse",43); arr[2] = new Goods("xiaomiMouse",12); arr[3] = new Goods("huaweiMouse",65); arr[4] = new Goods("microsoftMouse",43); Arrays.sort(arr); System.out.println(Arrays.toString(arr)); }
2. Customized sorting
Use of Comparator interface: custom sorting
1. Background:
When the element type does not implement Java Lang. comparable interface and inconvenient to modify code,
Or implement Java The collation of lang.comparable interface is not suitable for the current operation,
Then consider using Comparator objects to sort
2. Rewrite the compare(Object o1,Object o2) method to compare the sizes of o1 and o2:
If the method returns a positive integer, o1 is greater than o2;
If 0 is returned, it means equal;
Returns a negative integer indicating that o1 is less than o2.
@Test public void test3(){ String[] arr = new String[]{"AA","CC","KK","MM","GG","JJ","DD"}; Arrays.sort(arr,new Comparator(){ //Arrange strings in descending order @Override public int compare(Object o1, Object o2) { if(o1 instanceof String && o2 instanceof String){ String s1 = (String) o1; String s2 = (String) o2; return -s1.compareTo(s2); } // return 0; throw new RuntimeException("The data type entered is inconsistent"); } }); System.out.println(Arrays.toString(arr)); }
@Test public void test4(){ Goods[] arr = new Goods[6]; arr[0] = new Goods("lenovoMouse",34); arr[1] = new Goods("dellMouse",43); arr[2] = new Goods("xiaomiMouse",12); arr[3] = new Goods("huaweiMouse",65); arr[4] = new Goods("huaweiMouse",224); arr[5] = new Goods("microsoftMouse",43); Arrays.sort(arr, new Comparator() { //Specify the way to compare the size of goods: sort according to the product name from low to high, and then sort according to the price from high to low @Override public int compare(Object o1, Object o2) { if(o1 instanceof Goods && o2 instanceof Goods){ Goods g1 = (Goods)o1; Goods g2 = (Goods)o2; if(g1.getName().equals(g2.getName())){ return -Double.compare(g1.getPrice(),g2.getPrice()); }else{ return g1.getName().compareTo(g2.getName()); } } throw new RuntimeException("The data type entered is inconsistent"); } }); System.out.println(Arrays.toString(arr)); }
4, Use of other common classes
1.System
2.Math
3.BigInteger and BigDecimal
@Test public void test1() { String javaVersion = System.getProperty("java.version"); System.out.println("java of version:" + javaVersion); String javaHome = System.getProperty("java.home"); System.out.println("java of home:" + javaHome); String osName = System.getProperty("os.name"); System.out.println("os of name:" + osName); String osVersion = System.getProperty("os.version"); System.out.println("os of version:" + osVersion); String userName = System.getProperty("user.name"); System.out.println("user of name:" + userName); String userHome = System.getProperty("user.home"); System.out.println("user of home:" + userHome); String userDir = System.getProperty("user.dir"); System.out.println("user of dir:" + userDir); }
@Test public void test2() { BigInteger bi = new BigInteger("1243324112234324324325235245346567657653"); BigDecimal bd = new BigDecimal("12435.351"); BigDecimal bd2 = new BigDecimal("11"); System.out.println(bi); // System.out.println(bd.divide(bd2)); System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP)); System.out.println(bd.divide(bd2, 25, BigDecimal.ROUND_HALF_UP)); }
summary
I mainly write this article to make a note for myself and make it easy for you to read.