[Java -- time date class]

Posted by ChrisML123 on Fri, 31 Dec 2021 17:10:48 +0100

1.1 Date class

summary

java. util. The date class represents a specific moment, accurate to milliseconds.
Date has multiple constructors, but some of them are outdated, but some of them can convert millisecond values into date objects.

  • public Date(): allocates a Date object and initializes it to represent the time (in milliseconds) at which it was allocated.
  • public Date(long date): allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time (called epoch), i.e. 00:00 GMT, January 1, 1970).

tips: since we are in the East eighth District, our benchmark time is 8:0:0 on January 1, 1970.

To put it simply: using the nonparametric structure, you can automatically set the millisecond time of the current system time; Specify long type construction parameters, and you can customize the millisecond time. For example:

import java.util.Date;

public class Demo01Date {
    public static void main(String[] args) {
        // Create a date object and put the current time
        System.out.println(new Date()); // Tue Jan 16 14:37:35 CST 2018
        // Create a date object and convert the current millisecond value into a date object
        System.out.println(new Date(0L)); // Thu Jan 01 08:00:00 CST 1970
    }
}

tips: when using the println method, the toString method in the Date class will be called automatically. The Date class overrides the toString method in the Object class, so the result is a string in the specified format.

common method

Most of the methods in the Date class are outdated. The common methods are:

  • public long getTime() converts the date object to the corresponding time millisecond value.
 System.out.println(new Date().getTime());

1.2. DateFormat class

java.text.DateFormat is an abstract class of date / time formatting subclass. Through this class, we can help us complete the conversion between date and text, that is, we can convert back and forth between Date object and String object.

  • Format: convert from Date object to String object according to the specified format.
  • Parsing: converts a String object to a Date object in the specified format.

Construction method

Because DateFormat is an abstract class and cannot be used directly, it needs a common subclass Java text. SimpleDateFormat. This class needs a pattern (format) to specify the standard for formatting or parsing. The construction method is:

  • public SimpleDateFormat(String pattern): construct SimpleDateFormat with the date format symbols of the given schema and default locale.

The parameter pattern is a string representing the custom format of date and time.

Format Rules

Identification letters (case sensitive)meaning
yyear
Mmonth
dday
HTime
mbranch
ssecond

The code to create the SimpleDateFormat object is as follows:

import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class Demo02SimpleDateFormat {
    public static void main(String[] args) {
        // Corresponding date format: 2018-01-16 15:06:38
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }    
}

common method

Common methods of DateFormat class are:

  • public String format(Date date): formats the Date object as a string.
  • public Date parse(String source): parses a string into a Date object.

format method

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
 Convert Date object to String
*/
public class Demo03DateFormatMethod {
    public static void main(String[] args) {
        Date date = new Date();
        // Create a date format object. You can specify the style when obtaining the format object
        DateFormat df = new SimpleDateFormat("yyyy year MM month dd day");
        String str = df.format(date);
        System.out.println(str); // Current system time
    }
}

parse method

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
 Convert String to Date object
*/
public class Demo04DateFormatMethod {
    public static void main(String[] args) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy year MM month dd day");
        String str = "2018 December 11";
        Date date = df.parse(str);
        System.out.println(date); // Tue Dec 11 00:00:00 CST 2018
    }
}

1.3 practice

Please use the date and time related API to calculate how many days a person has been born.
Idea:

1. Obtain the millisecond value corresponding to the current time

2. Get the MS value corresponding to your birth date

3. Subtract two times (current time – date of birth)
Code implementation:

public static void function() throws Exception {
	System.out.println("Please enter birth date format YYYY-MM-dd");
	// Get the date of birth and enter it with the keyboard
	String birthdayString = new Scanner(System.in).next();
	// Convert a Date string to a Date object
	// Create a SimpleDateFormat object to write the date pattern
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	// Call the parse method to convert the string into a date object
	Date birthdayDate = sdf.parse(birthdayString);	
	// Get today's Date object
	Date todayDate = new Date();	
	// Convert the two dates into millisecond values, and the method getTime of the Date class
	long birthdaySecond = birthdayDate.getTime();
	long todaySecond = todayDate.getTime();
	long secone = todaySecond-birthdaySecond;	
	if (secone < 0){
		System.out.println("Not yet born");
	} else {
		System.out.println(secone/1000/60/60/24);
	}
}

1.4 Calendar

concept

java.util.Calendar is a calendar class. It appears after Date and replaces many methods of Date. This class encapsulates all possible time information into static member variables for easy access. Calendar class is convenient to obtain various time attributes.

Acquisition method

Calendar is an abstract class. Due to language sensitivity, the calendar class is not created directly when creating objects, but through static methods. It returns subclass objects as follows:

Calendar static method

  • public static Calendar getInstance(): get a calendar using the default time zone and locale
import java.util.Calendar;

public class Demo06CalendarInit {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
    }    
}

common method

According to the API document of Calendar class, the common methods are:

  • public int get(int field): returns the value of the given calendar field.
  • public void set(int field, int value): sets the given calendar field to the given value.
  • public abstract void add(int field, int amount): adds or subtracts the specified amount of time for a given calendar field according to calendar rules.
  • public Date getTime(): returns a Date object representing this Calendar time value (millisecond offset from epoch to present).

Many member constants are provided in the Calendar class to represent a given Calendar field:

field valuemeaning
YEARyear
MONTHMonth (starting from 0, can be used with + 1)
DAY_OF_MONTHDay (day) of the month
HOURHour (12 hour system)
HOUR_OF_DAYHour (24-hour system)
MINUTEbranch
SECONDsecond
DAY_OF_WEEKDay of the week (day of the week, Sunday is 1, can be - 1)

get/set method

The get method is used to obtain the value of the specified field, and the set method is used to set the value of the specified field. The code usage demonstration:

import java.util.Calendar;

public class CalendarDemo {
    public static void main(String[] args) {
        //Create calendar class
        Calendar calendar = Calendar.getInstance();
        //Set year
        int year = calendar.get(Calendar.YEAR);
        //Set month
        int month = calendar.get(Calendar.MONTH)+1;
        //Set day
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        //Set week
        String[] arr = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
        String  week =arr[calendar.get(Calendar.DAY_OF_WEEK)-1] ;1.Array subscript starts from 0; two.The first day of a foreigner begins on Sunday
        System.out.println(year+"year"+month+"month"+day+"day"+"week"+week);
    }
}

import java.util.Calendar;

public class CalendarMethod {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, 2020);
        System.out.print(year + "year" + month + "month" + dayOfMonth + "day"); // January 17, 2020
    }
}

add method

The add method can add or subtract the value of the specified calendar field. If the second parameter is a positive number, add the offset; if it is a negative number, subtract the offset. Code such as:

import java.util.Calendar;

public class Demo08CalendarMethod {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        System.out.print(year + "year" + month + "month" + dayOfMonth + "day"); // January 17, 2018
        // Using the add method
        cal.add(Calendar.DAY_OF_MONTH, 2); // Plus 2 days
        cal.add(Calendar.YEAR, -3); // Minus 3 years
        System.out.print(year + "year" + month + "month" + dayOfMonth + "day"); // January 18, 2015; 
    }
}

getTime method

The getTime method in Calendar does not get the millisecond time, but the corresponding Date object.

import java.util.Calendar;
import java.util.Date;

public class Demo09CalendarMethod {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        System.out.println(date); // Tue Jan 16 16:03:09 CST 2018
    }
}

Tips:

The Western week starts on Sunday and China on Monday.

In the Calendar class, the month is represented by 0-11 for January to December.

The date has a size relationship. The later the time, the greater the time.

1.5 System class

java.lang.System class provides a large number of static methods to obtain System related information or System level operations. In the API document of System class, the common methods are:

  • public static long currentTimeMillis(): returns the current time in milliseconds.
  • Public static void array copy (object SRC, int srcpos, object DeST, int destpos, int length): copies the data specified in the array to another array.

1. currentTimeMillis method

In fact, the currentTimeMillis method is to obtain the millisecond difference between the current system time and 00:00 on January 1, 1970

import java.util.Date;

public class SystemDemo {
    public static void main(String[] args) {
       	//Gets the current time in milliseconds
        System.out.println(System.currentTimeMillis()); // 1516090531144
    }
}

practice

The time (in milliseconds) it takes to verify that the for loop prints numbers 1-9999

public class SystemTest1 {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            System.out.println(i);
        }
        long end = System.currentTimeMillis();
        System.out.println("Total time taken MS:" + (end - start));
    }
}

2. arraycopy method

  • Public static void array copy (object SRC, int srcpos, object DeST, int destpos, int length): copies the data specified in the array to another array.

The copy action of array is system level and has high performance. System. The arraycopy method has five parameters, which mean:

Parameter serial numberParameter nameParameter typeParameter meaning
1srcObjectSource array
2srcPosintSource array index start position
3destObjecttarget array
4destPosintTarget array index start position
5lengthintNumber of copied elements

practice

Copy the first three elements of src array to the first three positions of dest array. Before copying elements: src array elements [1,2,3,4,5], dest array elements [6,7,8,9,10]. After copying elements: src array elements [1,2,3,4,5], dest array elements [1,2,3,9,10]

import java.util.Arrays;

public class Demo11SystemArrayCopy {
    public static void main(String[] args) {
        int[] src = new int[]{1,2,3,4,5};
        int[] dest = new int[]{6,7,8,9,10};
        System.arraycopy( src, 0, dest, 0, 3);
        /*After the code runs: the elements in the two arrays have changed
         src Array elements [1,2,3,4,5]
         dest Array elements [1,2,3,9,10]
        */
    }
}

1.6. StringBuilder class

1 string splicing problem

Since the object content of the String class cannot be changed, a new object will always be created in memory whenever String splicing is performed. For example:

public class StringDemo {
    public static void main(String[] args) {
        String s = "Hello";
        s += "World";
        System.out.println(s);
    }
}

In the API, the String class is described as follows: strings are constants, and their values cannot be changed after creation.

According to this sentence, our code actually produces three strings, namely "hello", "World" and "HelloWorld". The reference variable s first points to the Hello object, and finally points to the spliced new string object, namely HelloWord.

It can be seen that if you splice strings, a new String object will be constructed each time, which is time-consuming and a waste of space. To solve this problem, you can use Java Lang.stringbuilder class.

2 overview of StringBuilder

Check Java Lang. StringBuilder API. StringBuilder is also called variable character sequence. It is a String buffer similar to String. The length and content of the sequence can be changed through some method calls.

Originally, StringBuilder is a string buffer, that is, it is a container that can hold many strings. And can perform various operations on the string.

It has an array inside to store the string content. When string splicing, new content is directly added to the array. StringBuilder will automatically maintain the expansion of the array. The principle is shown in the following figure: (16 character space by default, exceeding automatic expansion)

3. Construction method

According to the API document of StringBuilder, there are two common construction methods:

  • public StringBuilder(): construct an empty StringBuilder container.
  • public StringBuilder(String str): construct a StringBuilder container and add strings.
public class StringBuilderDemo {
    public static void main(String[] args) {
        StringBuilder sb1 = new StringBuilder();
        System.out.println(sb1); // (blank)
        // Using parametric construction
        StringBuilder sb2 = new StringBuilder("huida");
        System.out.println(sb2); // huida
    }
}

4. Common methods

There are two methods commonly used by StringBuilder:

  • public StringBuilder append(...): Adds the string form of any type of data and returns the current object itself.
  • public String toString(): converts the current StringBuilder object to a String object.

append method

The append method has multiple overloaded forms and can receive any type of parameter. Any data as a parameter will add the corresponding string content to StringBuilder. For example:

public class Demo02StringBuilder {
	public static void main(String[] args) {
		//create object
		StringBuilder builder = new StringBuilder();
		//Public StringBuilder append (any type)
		StringBuilder builder2 = builder.append("hello");
		//Compare it
		System.out.println("builder:"+builder);
		System.out.println("builder2:"+builder2);
		System.out.println(builder == builder2); //true
	    // Any type can be added
		builder.append("hello");
		builder.append("world");
		builder.append(true);
		builder.append(100);
		// In our development, we will encounter the case of returning an object after calling a method. Then continue calling the method with the returned object.
        // At this time, we can put the code together now, like the append method. The code is as follows
		//Chain programming
		builder.append("hello").append("world").append(true).append(100);
		System.out.println("builder:"+builder);
	}
}

Note: StringBuilder has overridden the toString method in Object.

toString method

Through the toString method, the StringBuilder object will be converted to an immutable String object. For example:

public class Demo16StringBuilder {
    public static void main(String[] args) {
        // Chain creation
        StringBuilder sb = new StringBuilder("Hello").append("World").append("Java");
        // Call method
        String str = sb.toString();
        System.out.println(str); // HelloWorldJava
    }
}

1.6 packaging

1. Overview

Java provides two type systems, basic type and reference type. Using basic types is efficient. However, in many cases, objects will be created for use, because objects can do more functions. If you want our basic types to operate like objects, you can use the wrapper classes corresponding to the basic types, as follows:

Basic typeCorresponding wrapper class (in java.lang package)
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

2. Packing and unpacking

The process of back and forth conversion between the basic type and the corresponding packing class object is called "packing" and "unpacking":

  • Boxing: convert from basic type to corresponding wrapper class object.
  • Unpacking: convert from packing class object to corresponding basic type.

Take Integer and int as an example: (just understand the code)

Basic value - > packing object

Integer i = new Integer(4);//Using constructor functions
Integer iii = Integer.valueOf(4);//Use the valueOf method in the wrapper class

Packing object ----- > basic value

int num = i.intValue();

3. Automatic packing and unpacking

Since we often need to convert between basic types and packaging classes, starting from Java 5 (JDK 1.5), the boxing and unpacking of basic types and packaging classes can be completed automatically. For example:

Integer i = 4;//Automatic packing. Equivalent to integer I = integer valueOf(4);
i = i + 5;//Right of the equal sign: convert the I object to the basic value (automatic unpacking) i.intValue() + 5;
//After the addition operation is completed, box again and convert the basic value into an object.

4. 1 conversion between basic type and string

Convert basic type to String

There are three ways to convert a basic type to a String. You can see from the materials after class that only the simplest way is discussed here:

The basic type can be directly connected with ""; For example: 34+""

String is converted to the corresponding basic type

Except for the Character class, all other wrapper classes have parseXxx static methods that can convert string parameters to corresponding basic types:

  • public static byte parseByte(String s): converts a string parameter to the corresponding byte basic type.
  • public static short parseShort(String s): converts a string parameter to the corresponding short basic type.
  • public static int parseInt(String s): converts a string parameter to the corresponding int basic type.
  • public static long parseLong(String s): converts a string parameter to the corresponding long basic type.
  • public static float parseFloat(String s): converts a string parameter to the corresponding float basic type.
  • public static double parseDouble(String s): converts a string parameter to the corresponding double basic type.
  • public static boolean parseBoolean(String s): converts a string parameter to the corresponding boolean basic type.

Code usage (only take the static method parseXxx of Integer class as an example), such as:

public class Demo18WrapperParse {
    public static void main(String[] args) {
        int num = Integer.parseInt("100");
    }
}

Note: if the content of the string parameter cannot be correctly converted to the corresponding basic type, Java. Java. XML will be thrown Lang.numberformatexception exception.

Topics: Java