Java–Date string usage

Operation string dates, etc.

1. String concatenation

public class Test {
    public static void main1(String[] args) {
        String str1 = "hello,";
        String str2 = "my name is Tom!";
        String str3 = str1 + str2;
        System.out.println(str3);
    }
    //The running results are as follows:
    // hello, my name is Tom!
    
    public static void main2(String[] args) {
        System.out.println(10 + 2.5 + "price");
        // Perform arithmetic operations first, then perform string concatenation
        System.out.println("price" + 10 + 2.5);
        // Perform string concatenation
    }
    //The running results are as follows:
    // 12.5price
    // price102.5
}

2. String comparison

The String class in a.ava provides several methods for comparing strings. The most commonly used method is equals(), which compares two strings for equality and returns a boolean value. The usage format is as follows: str1.equals(str2); the equals() method will compare each character in the two strings. The same letters have different meanings if their case is different. For example the following code:

public class Test {
    public static void main(String[] args) {
        String str1 = "hello";
        String str2 = "HELLO";
        System.out.println(str1.equalsIgnoreCase(str2));
    }
    //The running results are as follows:
    // true
}

3. String interception

a. The so-called interception is to intercept a part of the string from a certain string as a new string. The substring method is provided in the String class to implement the interception function. The usage format is as follows: String substring (int beginIndex); or String substring (int beginIndex, int endIndex); The position of the first character of the string is 0

public class Test {
    public static void main(String[] args) {
        String str1 = "I Love Java!";
        String subs1 = str1.substring(2);
        //Intercept the string, intercept it from the starting position 2
        String subs2 = str1.substring(2, 6);
        //Intercept the string, intercept the part between 2-6
    
        System.out.println("Intercepted from starting position 2");
        System.out.println(subs1);
        System.out.println("Intercepted from position 2-6");
        System.out.println(subs2);
    }
    //The running results are as follows:
    // Intercept from starting position 2
    // Love Java
    // Taken from positions 2-6
    // Love
}

4. String search

a. String search refers to searching for another string in a string. The indexOf method is provided in the String class to implement the search function. The usage format is as follows:
str.indexOf(string substr) or str.indexOf(string substr, fromIndex)
The first is to search from the beginning of the specified string. The second is to search from the specified string and specify the starting position. Simply put, it is to get the subscript (index). For example:

public class Test {
    public static void main(String[] args) {
        String str1 = "I Love Java!";
        String str2 = "Love";
        int index1 = str1.indexOf(str2);
        // Find the "Love" string from the beginning
        int index2 = str1.indexOf(str2, 2);
        // Search for the "Love" string starting from index 2
        System.out.println(index1);
        System.out.println(index2);
    }
    //The running results are as follows:
    // 2
    // 2
    // Here is a special explanation: if the search string does not exist or does not exist, -1 will be returned (my compiler here)
}

5. Strings and character arrays

a. Sometimes you encounter the problem of converting strings and character arrays to each other. You can easily convert the character array into a string, and then use the properties and methods of the string object to further process the string. For example:

public class Test {
    public static void main(String[] args) {
        char[] helloArray = {'h','e','l','l','o'};
        // Use character array as parameter of constructor
        String helloString = new String(helloArray);
        System.out.println(helloString);
    }
    //The running results are as follows:
    // hello
}

b. When using the new operator to create a string object, using the string as a parameter of the constructor can convert the character array into a string corresponding to the character. Conversely, you can convert a string to a character array using toCharArray(), a method of the String object. It returns a character array converted from a string object. For example

public class Test {
    public static void main(String[] args) {
        String helloString = "hello";
        char[] helloArray = helloString.toCharArray(); // Convert string to character array
        for (int i = 0; i < helloArray.length; i + + ) {
            System.out.println(helloArray[i]);
        }
    }
    //The running results are as follows:
    //h
    //e
    //l
    //l
    //o
}

6. Get today’s date

a.LocalDate in Java 8 is used to represent today’s date. Unlike java.util.Date, it only has dates and does not include time. Use this class when you only need to represent dates.

package com.shxt.demo02;
 
import java.time.LocalDate;
 
public class Demo01 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("Today's date:" + today);
    }
}

7. Obtain year, month and day information respectively

package com.shxt.demo02;
 
import java.time.LocalDate;
 
public class Demo02 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();
 
        System.out.println("year:" + year);
        System.out.println("month:" + month);
        System.out.println("day:" + day);
 
    }
}

8. Determine whether two dates are equal

package com.shxt.demo02;
 
import java.time.LocalDate;
 
public class Demo04 {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.now();
 
        LocalDate date2 = LocalDate.of(2018,2,5);
 
        if(date1.equals(date2)){
            System.out.println("Times are equal");
        }else{
            System.out.println("Time does not wait");
        }
 
    }
}

9. Check for recurring events like birthdays

package com.shxt.demo02;
 
import java.time.LocalDate;
import java.time.MonthDay;
 
public class Demo05 {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.now();
 
        LocalDate date2 = LocalDate.of(2018,2,6);
        MonthDay birthday = MonthDay.of(date2.getMonth(),date2.getDayOfMonth());
        MonthDay currentMonthDay = MonthDay.from(date1);
 
        if(currentMonthDay.equals(birthday)){
            System.out.println("It's your birthday");
        }else{
            System.out.println("Your birthday has not arrived yet");
        }
 
    }
}

10. Get the current time

a. Use java.time to obtain

package com.shxt.demo02;
 
import java.time.LocalTime;
 
public class Demo06 {
    public static void main(String[] args) {
        LocalTime time = LocalTime.now();
        System.out.println("Get the current time, without date:" + time);
 
    }
}

b. Obtain through Date in Util package

 Date dates = new Date();
       SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMddHHmmss");
       System.out.println(dateFormat.format(dates));

c. Obtain through Calendar of Util package

 Calendar calendar= Calendar.getInstance();
    SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    System.out.println(dateFormat.format(calendar.getTime()));

11. Calculate the date one week later

a.LocalDate date does not contain time information. Its plus() method is used to add days, weeks, and months. The ChronoUnit class declares these time units. Since LocalDate is also an immutable type, you must use variables to assign values after returning.

package com.shxt.demo02;
 
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
 
public class Demo08 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("Today's date is:" + today);
        LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
        System.out.println("The date one week later is:" + nextWeek);
 
    }
}

12. Calculate the date one year ago and the date one year later

package com.shxt.demo02;
 
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
 
public class Demo09 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
 
        LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
        System.out.println("Date one year ago: " + previousYear);
 
        LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
        System.out.println("Date one year later:" + nextYear);
 
    }
}

13. How to determine whether a date is earlier or later than another date using Java

a. Another common operation in work is how to determine whether a given date is greater than or less than a certain day? In Java 8, the LocalDate class has two methods isBefore() and isAfter() for comparing dates. When calling the isBefore() method, it returns true if the given date is less than the current date.

package com.shxt.demo02;
 
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
 
 
public class Demo11 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
 
        LocalDate tomorrow = LocalDate.of(2018,2,6);
        if(tomorrow.isAfter(today)){
            System.out.println("The date after:" + tomorrow);
        }
 
        LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);
        if(yesterday.isBefore(today)){
            System.out.println("Previous date:" + yesterday);
        }
    }
}

14. How to check leap year in Java 8

package com.shxt.demo02;
 
import java.time.LocalDate;
 
public class Demo14 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        if(today.isLeapYear()){
            System.out.println("This year is Leap year");
        }else {
            System.out.println("2018 is not a Leap year");
        }
 
    }
}

15. Get the current timestamp in Java 8

The a.Instant class has a static factory method now() that returns the current timestamp, as shown below:

package com.shxt.demo02;
 
import java.time.Instant;
 
public class Demo16 {
    public static void main(String[] args) {
        Instant timestamp = Instant.now();
        System.out.println("What is value of this instant " + timestamp.toEpochMilli());
    }
}

16. Convert string to date type

package com.shxt.demo02;
 
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
 
public class Demo18 {
    public static void main(String[] args) {
        LocalDateTime date = LocalDateTime.now();
 
        DateTimeFormatter format1 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        //Convert date to string
        String str = date.format(format1);
 
        System.out.println("Convert date to string:" + str);
 
        DateTimeFormatter format2 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        //Convert string to date
        LocalDate date2 = LocalDate.parse(str,format2);
        System.out.println("Date type:" + date2);
 
    }
}

17. Generate random numbers

import java.util.Date;
  
public class DateDemo {
   public static void main(String args[]) {
       
    int uusid = (int)(Math.random()*100 + 1);
       
       System.out.println(uusid);
   }
}

18. Generate 6-digit random alphanumeric characters

public class test
{

    public static void main(String[] args)
    {
        //Randomly using character array
        String randomcode2 = "";
        String model = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        char[] m = model.toCharArray();
        
        for (int j=0;j<6;j + + )
        {
            char c = m[(int)(Math.random()*model.length())];
            randomcode2 = randomcode2 + c;
        }
        
        System.out.println(randomcode2);
     
    }

1.The difference between equals() and ==

– “==”: Determine whether the addresses of two objects are equal. That is, determine whether two objects are the same object.
– equals(): Determine whether the contents of two objects are equal.