Java核心类库(上)

参加拉勾教育大数据训练营课程笔记

学会查阅API文档,根据包索引,搜索等。

常用类

  • java.lang - 唯一一个Java虚拟机自动访问,所以System等不需要import就可以使用,例如:System, String等。
  • java.util - 提供大量工具类和集合类等,例如:Scanner , List, Random等。
  • java.io - 输入输出包,提供了文件读写,流读写等,例如:FileInputStream, FileOutputStream等。
  • java.net - 提供网络编程类,例如:ServerSocket类, Socket类等。
  • java.sql - 提供数据库访问类,数据操作的类和接口,例如:DriverManager类, Connection接口等。

需要记忆大量的核心类、接口。

java.lang

Object

Java中所有类的父类(根类),所有类都直接或间接继承自Object。没有显示使用extends关键字指定父类的类,其父类都是Object。而有明确父类的类也都间接继承自Object类。

常用方法:

Modifier and Type Method Description
protected Object clone() Creates and returns a copy of this object.
boolean equals(Object obj) Indicates whether some other object is “equal to” this one.
protected void finalize() Deprecated. The finalization mechanism is inherently problematic.
Class<?> getClass() Returns the runtime class of this Object.
int hashCode() Returns a hash code value for the object.
void notify() Wakes up a single thread that is waiting on this object’s monitor.
void notifyAll() Wakes up all threads that are waiting on this object’s monitor.
String toString() Returns a string representation of the object.
void wait() Causes the current thread to wait until it is awakened, typically by being notified or interrupted.
void wait(long timeoutMillis) Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.
void wait(long timeoutMillis, int nanos) Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.

重写equalshashCodetoString方法

  • equalshashCode必须保持一致性
  • toString方法默认返回对象地址

Notes

==操作符笔记地址,由于基本数据类型,内存空间本就是保存的实际数据值,所以可以直接使用==判断相等,而对象则是保存的指向堆区的地址,所以对象判断相等需要使用equals方法,而equals方法默认是比较地址,所以当需要自定义两个对象相等条件时,需要重写equals方法。

package module2.code.overridetest;import java.util.Objects;public class Student {private String name;private int age;public Student(String name, int age) {this.name = name;this.age = age;}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Student student = (Student) o;return age == student.age && name.equals(student.name);}@Overridepublic int hashCode() {return Objects.hash(name, age);}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}
}

包装类

基本数据类型不是对象,为了使基本类型也是对象,Java提供对基本数据类型进行对象化的类,称作包装类

包装类 对应的基本类型
java.lang.Byte byte
java.lang.Short short
java.lang.Integer int
java.lang.Long long
java.lang.Float float
java.lang.Double double
java.lang.Boolean boolean
java.lang.Character char

装箱(boxing)和拆箱(unboxing)

装箱:基本数据类型 → \to →对象

Integer it = Integer.valueOf(123);

拆箱:对象 → \to →基本数据类型

int ia = it.intValue();

从Java 1.5开始,增加了自动装箱和拆箱,无需再显示调用方法来实现装箱和拆箱

Integer it = 100;
int ia = it;

考点:

Integer it6 = 127; //128;
Integer it7 = 127; //128;
Integer it8 = new Integer(127); //new Integer(128);
Integer it9 = new Integer(127); //new Integer(128);
System.out.println(it6 == it7);      // 比较地址  false  true  地址一样
System.out.println(it6.equals(it7)); // 比较内容  true
System.out.println(it8 == it9);      // 比较地址  false
System.out.println(it8.equals(it9)); // 比较内容  true

Integer

  • java.lang.Object

    • java.lang.Number

      • java.lang.Integer

All Implemented Interfaces:

Serializable, Comparable<Integer>

public final class Integer
extends Number
implements Comparable<Integer>

常用常量

Modifier and Type Field Description
static int BYTES The number of bytes used to represent an int value in two’s complement binary form.
static int MAX_VALUE A constant holding the maximum value an int can have, 231-1.
static int MIN_VALUE A constant holding the minimum value an int can have, -231.
static int SIZE The number of bits used to represent an int value in two’s complement binary form.
static Class<Integer> TYPE The Class instance representing the primitive type int.

常用方法

Modifier and Type Method Description
int intValue() Returns the value of this Integer as an int.
long longValue() Returns the value of this Integer as a long after a widening primitive conversion.
boolean equals(Object obj) Compares this object to the specified object.
String toString() Returns a String object representing this Integer's value.
static Integer valueOf(int i) Returns an Integer instance representing the specified int value.
static int bitCount(int i) Returns the number of one-bits in the two’s complement binary representation of the specified int value.
static Integer valueOf(String s) Returns an Integer object holding the value of the specified String.
static Integer valueOf(String s, int radix) Returns an Integer object holding the value extracted from the specified String when parsed with the radix given by the second argument.
static int parseInt(String s) Parses the string argument as a signed decimal integer.
static String toBinaryString(int i) Returns a string representation of the integer argument as an unsigned integer in base 2.
static String toHexString(int i) Returns a string representation of the integer argument as an unsigned integer in base 16.
static String toOctalString(int i) Returns a string representation of the integer argument as an unsigned integer in base 8.

Double

  • java.lang.Object

    • java.lang.Number

      • java.lang.Double

All Implemented Interfaces:

Serializable, Comparable<Integer>

public final class Double
extends Number
implements Comparable<Double>

常用常量

Modifier and Type Field Description
static int BYTES The number of bytes used to represent a double value.
static int MAX_EXPONENT Maximum exponent a finite double variable may have.
static double MAX_VALUE A constant holding the largest positive finite value of type double, (2-2-52)·21023.
static int MIN_EXPONENT Minimum exponent a normalized double variable may have.
static double MIN_NORMAL A constant holding the smallest positive normal value of type double, 2-1022.
static double MIN_VALUE A constant holding the smallest positive nonzero value of type double, 2-1074.
static double NaN A constant holding a Not-a-Number (NaN) value of type double.
static double NEGATIVE_INFINITY A constant holding the negative infinity of type double.
static double POSITIVE_INFINITY A constant holding the positive infinity of type double.
static int SIZE The number of bits used to represent a double value.
static Class<Double> TYPE The Class instance representing the primitive type double.

常用方法

Modifier and Type Method Description
byte byteValue() Returns the value of this Double as a byte after a narrowing primitive conversion.
double doubleValue() Returns the double value of this Double object.
boolean equals(Object obj) Compares this object against the specified object.
String toString() Returns a string representation of this Double object.
boolean isNaN() Returns true if this Double value is a Not-a-Number (NaN), false otherwise.
static Double valueOf(double d) Returns a Double instance representing the specified double value.
static Double valueOf(String s) Returns a Double object holding the double value represented by the argument string s.
static double parseDouble(String s) Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.

Notes

java.lang.Number是一个抽象类,是数字类型所有类(java.lang.Byte, java.lang.Short, java.lang.Integer, java.lang.Long, java.lang.Float, java.lang.Double)的父类,用来描述他们的共有成员

Boolean

  • java.lang.Object

    • java.lang.Boolean

All Implemented Interfaces:

Serializable, Comparable<Boolean>

public final class Boolean
extends Object
implements Serializable, Comparable<Boolean>

常用常量

Modifier and Type Field Description
static Boolean FALSE The Boolean object corresponding to the primitive value false.
static Boolean TRUE The Boolean object corresponding to the primitive value true.
static Class<Boolean> TYPE The Class object representing the primitive type boolean.

常用方法

Modifier and Type Method Description
boolean booleanValue() Returns the value of this Boolean object as a boolean primitive.
boolean equals(Object obj) Returns true if and only if the argument is not null and is a Boolean object that represents the same boolean value as this object.
String toString() Returns a String object representing this Boolean’s value.
static Boolean valueOf(boolean b) Returns a Boolean instance representing the specified boolean value.
static Boolean valueOf(String s) Returns a Boolean with a value represented by the specified string.
static boolean parseBoolean(String s) Parses the string argument as a boolean (return true only when s = “true”, ignore case).
public static boolean parseBoolean(String s) {return "true".equalsIgnoreCase(s);
}

Character

  • java.lang.Object

    • java.lang.Character

All Implemented Interfaces:

Serializable, Comparable<Boolean>

public final class Character
extends Object
implements Serializable, Comparable<Character>

常用常量

Modifier and Type Field Description
static int BYTES The number of bytes used to represent a char value in unsigned binary form.
static int SIZE The number of bits used to represent a char value in unsigned binary form, constant 16.
static Class<Character> TYPE The Class instance representing the primitive type char.

常用方法

Modifier and Type Method Description
char charValue() Returns the value of this Character object.
boolean equals(Object obj) Compares this object against the specified object.
String toString() Returns a String object representing this Character's value.
static Character valueOf(char c) Returns a Character instance representing the specified char value.
static boolean isUpperCase(char ch) Determines if the specified character is an uppercase character.
static boolean isLowerCase(char ch) Determines if the specified character is a lowercase character.
static boolean isWhitespace(char ch) Determines if the specified character is white space according to Java.
static boolean isDigit(char ch) Determines if the specified character is a digit.
static boolean isAlphabetic(int codePoint) Determines if the specified character (Unicode code point) is an alphabet.
static char toUpperCase(char ch) Converts the character argument to uppercase using case mapping information from the UnicodeData file.
static char toLowerCase(char ch) Converts the character argument to lowercase using case mapping information from the UnicodeData file.

数学处理类

Math

  • java.lang.Object

    • java.lang.Math
public final class Math
extends Object

常用方法

Modifier and Type Method Description
static double abs(double a) Returns the absolute value of a double value.
static float abs(float a) Returns the absolute value of a float value.
static int abs(int a) Returns the absolute value of an int value.
static long abs(long a) Returns the absolute value of a long value.
static double max(double a, double b) Returns the greater of two double values.
static float max(float a, float b) Returns the greater of two float values.
static int max(int a, int b) Returns the greater of two int values.
static long max(long a, long b) Returns the greater of two long values.
static double min(double a, double b) Returns the smaller of two double values.
static float min(float a, float b) Returns the smaller of two float values.
static int min(int a, int b) Returns the smaller of two int values.
static long min(long a, long b) Returns the smaller of two long values.
static double pow(double a, double b) Returns the value of the first argument raised to the power of the second argument.
static double random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
static double sqrt(double a) Returns the correctly rounded positive square root of a double value.
static long round(double a) Returns the closest long to the argument, with ties rounding to positive infinity.
static int round(float a) Returns the closest int to the argument, with ties rounding to positive infinity.

BigDecimal

实现浮点数的精确计算

  • java.lang.Object

    • java.lang.Number

      • java.math.BigDecimal

All Implemented Interfaces:

Serializable, Comparable<Integer>

public class BigDecimal
extends Number
implements Comparable<BigDecimal>

常用变量

Modifier and Type Field Description
static BigDecimal ONE The value 1, with a scale of 0.
static int ROUND_CEILING **Deprecated.**Use RoundingMode.CEILING instead.
static int ROUND_DOWN **Deprecated.**Use RoundingMode.DOWN instead.
static int ROUND_FLOOR **Deprecated.**Use RoundingMode.FLOOR instead.
static int ROUND_HALF_DOWN **Deprecated.**Use RoundingMode.HALF_DOWN instead.
static int ROUND_HALF_EVEN **Deprecated.**Use RoundingMode.HALF_EVEN instead.
static int ROUND_HALF_UP **Deprecated.**Use RoundingMode.HALF_UP instead.
static int ROUND_UNNECESSARY **Deprecated.**Use RoundingMode.UNNECESSARY instead.
static int ROUND_UP **Deprecated.**Use RoundingMode.UP instead.
static BigDecimal TEN The value 10, with a scale of 0.
static BigDecimal ZERO The value 0, with a scale of 0.

构造方法

Constructor Description
BigDecimal(String val) Translates the string representation of a BigDecimal into a BigDecimal.

常用方法

Modifier and Type Method Description
BigDecimal abs() Returns a BigDecimal whose value is the absolute value of this BigDecimal, and whose scale is this.scale().
BigDecimal add(BigDecimal augend) Returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(), augend.scale()).
BigDecimal subtract(BigDecimal subtrahend) Returns a BigDecimal whose value is (this - subtrahend), and whose scale is max(this.scale(), subtrahend.scale()).
BigDecimal multiply(BigDecimal multiplicand) Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).
BigDecimal divide(BigDecimal divisor) Returns a BigDecimal whose value is (this / divisor), and whose preferred scale is (this.scale() - divisor.scale()); if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.
BigDecimal pow(int n) Returns a BigDecimal whose value is (thisn), The power is computed exactly, to unlimited precision.

BigInteger

表示比long更大的整数范围

  • java.lang.Object

    • java.lang.Number

      • java.math.BigInteger

All Implemented Interfaces:

Serializable, Comparable<Integer>

public class BigInteger
extends Number
implements Comparable<BigInteger>

常量

Modifier and Type Field Description
static BigInteger ONE The BigInteger constant one.
static BigInteger TEN The BigInteger constant ten.
static BigInteger TWO The BigInteger constant two.
static BigInteger ZERO The BigInteger constant zero.

构造方法

Constructor Description
BigInteger(String val) Translates the decimal String representation of a BigInteger into a BigInteger.
BigInteger(String val, int radix) Translates the String representation of a BigInteger in the specified radix into a BigInteger.

常用方法

Modifier and Type Method Description
BigInteger abs() Returns a BigInteger whose value is the absolute value of this BigInteger.
BigInteger add(BigInteger val) Returns a BigInteger whose value is (this + val).
BigInteger subtract(BigInteger val) Returns a BigInteger whose value is (this - val).
BigInteger multiply(BigInteger val) Returns a BigInteger whose value is (this * val).
BigInteger divide(BigInteger val) Returns a BigInteger whose value is (this / val).
BigInteger remainder(BigInteger val) Returns a BigInteger whose value is (this % val).
BigInteger[] divideAndRemainder(BigInteger val) Returns an array of two BigIntegers containing (this / val) followed by (this % val).

String

  • java.lang.Object

    • java.math.String

All Implemented Interfaces:

Serializable, CharSequence, Comparable<Integer>

public final class String
extends Object
implements Serializable, Comparable<String>, CharSequence

final修饰,String类不能被继承。从Java 1.9开始底层不再使用char[]来存储,而是使用byte[]加上编码,从而节约了一些空间。String是常量,不可更改,因此可以被共享使用。

常量池

String描述的字符串内容不可改变,因此Java虚拟机将首次出现的字符串放入常量池中,若后续代码中出现了相同字符串内容则直接使用常量池中已有的字符串对象,而无需申请内存和创建对象,从而提高性能。

String str1 = "abc";
String str2 = "abc";
System.out.println(str1 == str2); // 比较地址  true

构造方法

Constructor Description
String() Initializes a newly created String object so that it represents an empty character sequence.
String(byte[] bytes) Constructs a new String by decoding the specified array of bytes using the platform’s default charset.
String(byte[] bytes, int offset, int length) Constructs a new String by decoding the specified subarray of bytes using the platform’s default charset.
String(char[] value) Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.
String(char[] value, int offset, int count) Allocates a new String that contains characters from a subarray of the character array argument.
String(byte[] bytes, String charsetName) Constructs a new String by decoding the specified array of bytes using the specified charset.
String(byte[] bytes, Charset charset) Constructs a new String by decoding the specified array of bytes using the specified charset.
String(String original) Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.

常用方法

Modifier and Type Method Description
char charAt(int index) Returns the char value at the specified index.
int length() Returns the length of this string.
boolean isBlank() Returns true if the string is empty or contains only white space codepoints, otherwise false.
boolean isEmpty() Returns true if, and only if, length() is 0.
int compareTo(String anotherString) Compares two strings lexicographically.
int compareToIgnoreCase(String str) Compares two strings lexicographically, ignoring case differences.
String concat(String str) Concatenates the specified string to the end of this string.
boolean contains(CharSequence s) Returns true if and only if this string contains the specified sequence of char values.
String toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale.
String toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale.
String trim() Returns a string whose value is this string, with all leading and trailing space removed, where space is defined as any character whose codepoint is less than or equal to 'U+0020' (the space character).
boolean startsWith(String prefix) Tests if this string starts with the specified prefix.
boolean startsWith(String prefix, int toffset) Tests if the substring of this string beginning at the specified index starts with the specified prefix.
boolean endsWith(String suffix) Tests if this string ends with the specified suffix.
boolean equals(Object anObject) Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString) Compares this String to another String, ignoring case considerations.
int hashCode() Returns a hash code for this string.
int indexOf(int ch) Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
int lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified character.
int lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
int lastIndexOf(String str) Returns the index within this string of the last occurrence of the specified substring.
int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
String substring(int beginIndex) Returns a string that is a substring of this string.
String substring(int beginIndex, int endIndex) Returns a string that is a substring of this string.
String repeat(int count) Returns a string whose value is the concatenation of this string repeated count times.

回文判断:

String str1 = new String("上海自来水来自海上");
System.out.println("str1 = " + str1); // 上海自来水来自海上
bool flag = true;
for (int i = 0; i < str1.length()/2; i++) {if (str1.charAt(i) != str1.charAt(str1.length()-i-1)) {break;}
}
System.out.println(flag ? "是回文!":"不是回文!");

正则表达式

String中与正则表达式相关的方法,正则内容太过复杂,将单独写一篇博客。

Modifier and Type Method Description
boolean matches(String regex) Tells whether or not this string matches the given regular expression.
String[] split(String regex) Splits this string around matches of the given regular expression.
String[] split(String regex, int limit) Splits this string around matches of the given regular expression.
String replace(char oldChar, char newChar) Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
String replace(CharSequence target, CharSequence replacement) Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
String replaceAll(String regex, String replacement) Replaces each substring of this string that matches the given regular expression with the given replacement.
String replaceFirst(String regex, String replacement) Replaces the first substring of this string that matches the given regular expression with the given replacement.

String笔试考点

  1. 使用两种方式实现字符串"12345"转换为整数12345并打印

    方式一

    String str2 = new String("12345");
    int ia = Integer.parseInt(str2);
    

    方式二

    String str2 = new String("12345");
    int ib = 0;
    for (int i = 0; i < str2.length(); i++) {ib = ib*10 + (str2.charAt(i) - '0');
    }
    
  2. 常量池

    // 1.请问下面的代码会创建几个对象?分别存放在什么地方?
    String str1 = "hello";  // 1个对象  存放在常量池中
    String str1 = new String("helo"); // 2个对象  1个在常量池中,1个在堆区// 2.常量池和堆区对象的比较
    String str1 = "hello";  // 常量池
    String str2 = "hello";  // 常量池
    String str3 = new String("hello"); // 堆区
    String str4 = new String("hello"); // 堆区
    System.out.println(str1 == str2);       // 比较地址  true
    System.out.println(str1.equals(str2));  // 比较内容  true
    System.out.println(str3 == str4);       // 比较地址  false
    System.out.println(str3.equals(str4));  // 比较内容  true
    System.out.println(str2 == str4);       // 比较地址  false
    System.out.println(str2.equals(str4));  // 比较内容 true// 3.常量有优化机制,变量没有
    String str5 = "abcd";
    String str6 = "ab" + "cd";  // 常量优化机制  "abcd"
    System.out.println(str5 == str6); // 比较地址  trueString str7 = "ab";
    String str8 = str7 + "cd"; // 没有常量优化
    System.out.println(str5 == str8); // 比较地址 false
    

正则表达式的使用

StringBuilderStringBuffer - 可变字符串

StringBuilder - not thread-safe, not synchronized

public final class StringBuilder
extends Object
implements Serializable, Comparable<StringBuilder>, CharSequence

A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization.

Constructors

Constructor Description
StringBuilder() Constructs a string builder with no characters in it and an initial capacity of 16 characters.
StringBuilder(int capacity) Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.
StringBuilder(CharSequence seq) Constructs a string builder that contains the same characters as the specified CharSequence.
StringBuilder(String str) Constructs a string builder initialized to the contents of the specified string.

Methods

Modifier and Type Method Description
StringBuffer append(String str) Appends the specified string to this character sequence.
StringBuffer append(StringBuffer sb) Appends the specified StringBuffer to this sequence.
int capacity() Returns the current capacity.
char charAt(int index) Returns the char value in this sequence at the specified index.
StringBuffer delete(int start, int end) Removes the characters in a substring of this sequence.
StringBuffer deleteCharAt(int index) Removes the char at the specified position in this sequence.
StringBuffer insert(int offset, String str) Inserts the string into this character sequence.
int lastIndexOf(String str) Returns the index within this string of the last occurrence of the specified substring.
int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
int length() Returns the length (character count).
StringBuffer replace(int start, int end, String str) Replaces the characters in a substring of this sequence with characters in the specified String.
StringBuffer reverse() Causes this character sequence to be replaced by the reverse of the sequence.
void setCharAt(int index, char ch) The character at the specified index is set to ch.
void setLength(int newLength) Sets the length of the character sequence.
String substring(int start) Returns a new String that contains a subsequence of characters currently contained in this character sequence.
String substring(int start, int end) Returns a new String that contains a subsequence of characters currently contained in this sequence.

StringBuffer - thread-safe, synchronized

public final class StringBuffer
extends Object
implements Serializable, Comparable<StringBuffer>, CharSequence

A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

Constructors

Constructor Description
StringBuffer() Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
StringBuffer(int capacity) Constructs a string buffer with no characters in it and the specified initial capacity.
StringBuffer(CharSequence seq) Constructs a string buffer that contains the same characters as the specified CharSequence.
StringBuffer(String str) Constructs a string buffer initialized to the contents of the specified string.

Methods

Modifier and Type Method Description
StringBuffer append(String str) Appends the specified string to this character sequence.
StringBuffer append(StringBuffer sb) Appends the specified StringBuffer to this sequence.
int capacity() Returns the current capacity.
char charAt(int index) Returns the char value in this sequence at the specified index.
StringBuffer delete(int start, int end) Removes the characters in a substring of this sequence.
StringBuffer deleteCharAt(int index) Removes the char at the specified position in this sequence.
StringBuffer insert(int offset, String str) Inserts the string into this character sequence.
int lastIndexOf(String str) Returns the index within this string of the last occurrence of the specified substring.
int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
int length() Returns the length (character count).
StringBuffer replace(int start, int end, String str) Replaces the characters in a substring of this sequence with characters in the specified String.
StringBuffer reverse() Causes this character sequence to be replaced by the reverse of the sequence.
void setCharAt(int index, char ch) The character at the specified index is set to ch.
void setLength(int newLength) Sets the length of the character sequence.
String substring(int start) Returns a new String that contains a subsequence of characters currently contained in this character sequence.
String substring(int start, int end) Returns a new String that contains a subsequence of characters currently contained in this sequence.

java.util.Date

获取当前时间

java.lang.System.currentTimeMillis()

Modifier and Type Method Description
static long currentTimeMillis() Returns the current time in milliseconds.
@Test
public void getCurrentTime() {final long l = System.currentTimeMillis();System.out.println(l);
}

Output:

1627390821407

Process finished with exit code 0

public class Date
extends Object
implements Serializable, Cloneable, Comparable<Date>

The class Date represents a specific instant in time, with millisecond precision.

Constructors

Constructor Description
Date() Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
Date(int year, int month, int date) Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
Date(int year, int month, int date, int hrs, int min) Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min) or GregorianCalendar(year + 1900, month, date, hrs, min).
Date(int year, int month, int date, int hrs, int min, int sec) Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec).
Date(long date) Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as “the epoch”, namely January 1, 1970, 00:00:00 GMT.
Date(String s) Deprecated. As of JDK version 1.1, replaced by DateFormat.parse(String s).

Methods

Modifier and Type Method Description
boolean after(Date when) Tests if this date is after the specified date.
boolean before(Date when) Tests if this date is before the specified date.
int compareTo(Date anotherDate) Compares two Dates for ordering.
boolean equals(Object obj) Compares two dates for equality.
static Date from(Instant instant) Obtains an instance of Date from an Instant object.
int getDate() **Deprecated.**As of JDK version 1.1, replaced by Calendar.get(Calendar.DAY_OF_MONTH).
int getDay() **Deprecated.**As of JDK version 1.1, replaced by Calendar.get(Calendar.DAY_OF_WEEK).
int getHours() **Deprecated.**As of JDK version 1.1, replaced by Calendar.get(Calendar.HOUR_OF_DAY).
int getMinutes() **Deprecated.**As of JDK version 1.1, replaced by Calendar.get(Calendar.MINUTE).
int getMonth() **Deprecated.**As of JDK version 1.1, replaced by Calendar.get(Calendar.MONTH).
int getSeconds() **Deprecated.**As of JDK version 1.1, replaced by Calendar.get(Calendar.SECOND).
long getTime() Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
int getTimezoneOffset() **Deprecated.**As of JDK version 1.1, replaced by -(Calendar.get(Calendar.ZONE_OFFSET) + Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000).
int getYear() **Deprecated.**As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.
int hashCode() Returns a hash code value for this object.
static long parse(String s) **Deprecated.**As of JDK version 1.1, replaced by DateFormat.parse(String s).
void setDate(int date) **Deprecated.**As of JDK version 1.1, replaced by Calendar.set(Calendar.DAY_OF_MONTH, int date).
void setHours(int hours) **Deprecated.**As of JDK version 1.1, replaced by Calendar.set(Calendar.HOUR_OF_DAY, int hours).
void setMinutes(int minutes) **Deprecated.**As of JDK version 1.1, replaced by Calendar.set(Calendar.MINUTE, int minutes).
void setMonth(int month) **Deprecated.**As of JDK version 1.1, replaced by Calendar.set(Calendar.MONTH, int month).
void setSeconds(int seconds) **Deprecated.**As of JDK version 1.1, replaced by Calendar.set(Calendar.SECOND, int seconds).
void setTime(long time) Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.
void setYear(int year) **Deprecated.**As of JDK version 1.1, replaced by Calendar.set(Calendar.YEAR, year + 1900).
String toGMTString() **Deprecated.**As of JDK version 1.1, replaced by DateFormat.format(Date date), using a GMT TimeZone.
Instant toInstant() Converts this Date object to an Instant.
String toLocaleString() **Deprecated.**As of JDK version 1.1, replaced by DateFormat.format(Date date).
String toString() Converts this Date object to a String of the form:
static long UTC(int year, int month, int date, int hrs, int min, int sec) **Deprecated.**As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec), using a UTC TimeZone, followed by Calendar.getTime().getTime().
@Test
public void newDate() {Date d = new Date();System.out.println(d);final long l = System.currentTimeMillis();Date d1 = new Date(l);System.out.println(d1);
}

Output

Tue Jul 27 23:16:17 CST 2021
Tue Jul 27 23:16:17 CST 2021

Process finished with exit code 0

SimpleDateFormat

public class SimpleDateFormat
extends DateFormat

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date → text), parsing (text → date), and normalization.

Constructors

Constructor Description
SimpleDateFormat() Constructs a SimpleDateFormat using the default pattern and date format symbols for the default FORMAT locale.
SimpleDateFormat(String pattern) Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the default FORMAT locale.
SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols) Constructs a SimpleDateFormat using the given pattern and date format symbols.
SimpleDateFormat(String pattern, Locale locale) Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the given locale.

Methods

Modifier and Type Method Description
String format(Date date) Formats a Date into a date-time string.
Date parse(String source) Parses text from the beginning of the given string to produce a date.
@Testpublic void simpleDateFormat() {final long l = System.currentTimeMillis();Date d1 = new Date(l);SimpleDateFormat simpleDateFormat = new SimpleDateFormat("y/MM/dd HH:mm:ss.S");System.out.println(simpleDateFormat.format(d1));}

Output:

2021/7/27 23:38:1.723

Process finished with exit code 0

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year (context sensitive) Month July; Jul; 07
L Month in year (standalone form) Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, …, 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00

Examples:

Date and Time Pattern Result
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u" 2001-W27-3

Calendar

public abstract class Calendar
extends Object
implements Serializable, Cloneable, Comparable<Calendar>

The Calendar class is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fieldssuch as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week. An instant in time can be represented by a millisecond value that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT (Gregorian).

The class also provides additional fields and methods for implementing a concrete calendar system outside the package. Those fields and methods are defined as protected.

Fields

Modifier and Type Field Description
static int ALL_STYLES A style specifier for getDisplayNames indicating names in all styles, such as “January” and “Jan”.
static int AM Value of the AM_PM field indicating the period of the day from midnight to just before noon.
static int AM_PM Field number for get and set indicating whether the HOUR is before or after noon.
static int APRIL Value of the MONTH field indicating the fourth month of the year in the Gregorian and Julian calendars.
protected boolean areFieldsSet True if fields[] are in sync with the currently set time.
static int AUGUST Value of the MONTH field indicating the eighth month of the year in the Gregorian and Julian calendars.
static int DATE Field number for get and set indicating the day of the month.
static int DAY_OF_MONTH Field number for get and set indicating the day of the month.
static int DAY_OF_WEEK Field number for get and set indicating the day of the week.
static int DAY_OF_WEEK_IN_MONTH Field number for get and set indicating the ordinal number of the day of the week within the current month.
static int DAY_OF_YEAR Field number for get and set indicating the day number within the current year.
static int DECEMBER Value of the MONTH field indicating the twelfth month of the year in the Gregorian and Julian calendars.
static int DST_OFFSET Field number for get and set indicating the daylight saving offset in milliseconds.
static int ERA Field number for get and set indicating the era, e.g., AD or BC in the Julian calendar.
static int FEBRUARY Value of the MONTH field indicating the second month of the year in the Gregorian and Julian calendars.
static int FIELD_COUNT The number of distinct fields recognized by get and set.
protected int[] fields The calendar field values for the currently set time for this calendar.
static int FRIDAY Value of the DAY_OF_WEEK field indicating Friday.
static int HOUR Field number for get and set indicating the hour of the morning or afternoon.
static int HOUR_OF_DAY Field number for get and set indicating the hour of the day.
protected boolean[] isSet The flags which tell if a specified calendar field for the calendar is set.
protected boolean isTimeSet True if then the value of time is valid.
static int JANUARY Value of the MONTH field indicating the first month of the year in the Gregorian and Julian calendars.
static int JULY Value of the MONTH field indicating the seventh month of the year in the Gregorian and Julian calendars.
static int JUNE Value of the MONTH field indicating the sixth month of the year in the Gregorian and Julian calendars.
static int LONG A style specifier for getDisplayName and getDisplayNames equivalent to LONG_FORMAT.
static int LONG_FORMAT A style specifier for getDisplayName and getDisplayNames indicating a long name used for format.
static int LONG_STANDALONE A style specifier for getDisplayName and getDisplayNames indicating a long name used independently, such as a month name as calendar headers.
static int MARCH Value of the MONTH field indicating the third month of the year in the Gregorian and Julian calendars.
static int MAY Value of the MONTH field indicating the fifth month of the year in the Gregorian and Julian calendars.
static int MILLISECOND Field number for get and set indicating the millisecond within the second.
static int MINUTE Field number for get and set indicating the minute within the hour.
static int MONDAY Value of the DAY_OF_WEEK field indicating Monday.
static int MONTH Field number for get and set indicating the month.
static int NARROW_FORMAT A style specifier for getDisplayName and getDisplayNames indicating a narrow name used for format.
static int NARROW_STANDALONE A style specifier for getDisplayName and getDisplayNames indicating a narrow name independently.
static int NOVEMBER Value of the MONTH field indicating the eleventh month of the year in the Gregorian and Julian calendars.
static int OCTOBER Value of the MONTH field indicating the tenth month of the year in the Gregorian and Julian calendars.
static int PM Value of the AM_PM field indicating the period of the day from noon to just before midnight.
static int SATURDAY Value of the DAY_OF_WEEK field indicating Saturday.
static int SECOND Field number for get and set indicating the second within the minute.
static int SEPTEMBER Value of the MONTH field indicating the ninth month of the year in the Gregorian and Julian calendars.
static int SHORT A style specifier for getDisplayName and getDisplayNames equivalent to SHORT_FORMAT.
static int SHORT_FORMAT A style specifier for getDisplayName and getDisplayNames indicating a short name used for format.
static int SHORT_STANDALONE A style specifier for getDisplayName and getDisplayNames indicating a short name used independently, such as a month abbreviation as calendar headers.
static int SUNDAY Value of the DAY_OF_WEEK field indicating Sunday.
static int THURSDAY Value of the DAY_OF_WEEK field indicating Thursday.
protected long time The currently set time for this calendar, expressed in milliseconds after January 1, 1970, 0:00:00 GMT.
static int TUESDAY Value of the DAY_OF_WEEK field indicating Tuesday.
static int UNDECIMBER Value of the MONTH field indicating the thirteenth month of the year.
static int WEDNESDAY Value of the DAY_OF_WEEK field indicating Wednesday.
static int WEEK_OF_MONTH Field number for get and set indicating the week number within the current month.
static int WEEK_OF_YEAR Field number for get and set indicating the week number within the current year.
static int YEAR Field number for get and set indicating the year.
static int ZONE_OFFSET Field number for get and set indicating the raw offset from GMT in milliseconds.

Constructors

Modifier Constructor Description
protected Calendar() Constructs a Calendar with the default time zone and the default FORMAT locale.
protected Calendar(TimeZone zone, Locale aLocale) Constructs a calendar with the specified time zone and locale.

Methods

Modifier and Type Method Description
abstract void add(int field, int amount) Adds or subtracts the specified amount of time to the given calendar field, based on the calendar’s rules.
boolean after(Object when) Returns whether this Calendar represents a time after the time represented by the specified Object.
boolean before(Object when) Returns whether this Calendar represents a time before the time represented by the specified Object.
void clear() Sets all the calendar field values and the time value (millisecond offset from the Epoch) of this Calendar undefined.
void clear(int field) Sets the given calendar field value and the time value (millisecond offset from the Epoch) of this Calendar undefined.
Object clone() Creates and returns a copy of this object.
int compareTo(Calendar anotherCalendar) Compares the time values (millisecond offsets from the Epoch) represented by two Calendar objects.
protected void complete() Fills in any unset fields in the calendar fields.
protected abstract void computeFields() Converts the current millisecond time value time to calendar field values in fields[\].
protected abstract void computeTime() Converts the current calendar field values in fields[\] to the millisecond time value time.
boolean equals(Object obj) Compares this Calendar to the specified Object.
int get(int field) Returns the value of the given calendar field.
int getActualMaximum(int field) Returns the maximum value that the specified calendar field could have, given the time value of this Calendar.
int getActualMinimum(int field) Returns the minimum value that the specified calendar field could have, given the time value of this Calendar.
static Set<String> getAvailableCalendarTypes() Returns an unmodifiable Set containing all calendar types supported by Calendar in the runtime environment.
static Locale[] getAvailableLocales() Returns an array of all locales for which the getInstance methods of this class can return localized instances.
String getCalendarType() Returns the calendar type of this Calendar.
String getDisplayName(int field, int style, Locale locale) Returns the string representation of the calendar field value in the given style and locale.
Map<String,Integer> getDisplayNames(int field, int style, Locale locale) Returns a Map containing all names of the calendar field in the given style and locale and their corresponding field values.
int getFirstDayOfWeek() Gets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France.
abstract int getGreatestMinimum(int field) Returns the highest minimum value for the given calendar field of this Calendar instance.
static Calendar getInstance() Gets a calendar using the default time zone and locale.
static Calendar getInstance(Locale aLocale) Gets a calendar using the default time zone and specified locale.
static Calendar getInstance(TimeZone zone) Gets a calendar using the specified time zone and default locale.
static Calendar getInstance(TimeZone zone, Locale aLocale) Gets a calendar with the specified time zone and locale.
abstract int getLeastMaximum(int field) Returns the lowest maximum value for the given calendar field of this Calendar instance.
abstract int getMaximum(int field) Returns the maximum value for the given calendar field of this Calendar instance.
int getMinimalDaysInFirstWeek() Gets what the minimal days required in the first week of the year are; e.g., if the first week is defined as one that contains the first day of the first month of a year, this method returns 1.
abstract int getMinimum(int field) Returns the minimum value for the given calendar field of this Calendar instance.
Date getTime() Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").
long getTimeInMillis() Returns this Calendar’s time value in milliseconds.
TimeZone getTimeZone() Gets the time zone.
int getWeeksInWeekYear() Returns the number of weeks in the week year represented by this Calendar.
int getWeekYear() Returns the week year represented by this Calendar.
int hashCode() Returns a hash code for this calendar.
protected int internalGet(int field) Returns the value of the given calendar field.
boolean isLenient() Tells whether date/time interpretation is to be lenient.
boolean isSet(int field) Determines if the given calendar field has a value set, including cases that the value has been set by internal fields calculations triggered by a get method call.
boolean isWeekDateSupported() Returns whether this Calendar supports week dates.
abstract void roll(int field, boolean up) Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
void roll(int field, int amount) Adds the specified (signed) amount to the specified calendar field without changing larger fields.
void set(int field, int value) Sets the given calendar field to the given value.
void set(int year, int month, int date) Sets the values for the calendar fields YEAR, MONTH(starts from 0), and DAY_OF_MONTH.
void set(int year, int month, int date, int hourOfDay, int minute) Sets the values for the calendar fields YEAR, MONTH, DAY_OF_MONTH, HOUR_OF_DAY, and MINUTE.
void set(int year, int month, int date, int hourOfDay, int minute, int second) Sets the values for the fields YEAR, MONTH, DAY_OF_MONTH, HOUR_OF_DAY, MINUTE, and SECOND.
void setFirstDayOfWeek(int value) Sets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France.
void setLenient(boolean lenient) Specifies whether or not date/time interpretation is to be lenient.
void setMinimalDaysInFirstWeek(int value) Sets what the minimal days required in the first week of the year are; For example, if the first week is defined as one that contains the first day of the first month of a year, call this method with value 1.
void setTime(Date date) Sets this Calendar’s time with the given Date.
void setTimeInMillis(long millis) Sets this Calendar’s current time from the given long value.
void setTimeZone(TimeZone value) Sets the time zone with the given time zone value.
void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) Sets the date of this Calendar with the given date specifiers - week year, week of year, and day of week.
Instant toInstant() Converts this object to an Instant.
String toString() Return a string representation of this calendar.

Parameter month in set method starts from 0 (Calendar.JULY=6).

Calendar calendar = Calendar.getInstance();  // return Calendar's extended class instance
calendar.set(2021, Calendar.JULY, 29, 22, 9);
calendar.set(Calendar.YEAR, 2019);
calendar.set(Calendar.MONTH, Calendar.DECEMBER);
calendar.set(Calendar.HOUR, 8);
calendar.add(Calendar.HOUR, 2);

GregorianCalendar

public class GregorianCalendar
extends Calendar

Constructors

Constructor Description
GregorianCalendar() Constructs a default GregorianCalendar using the current time in the default time zone with the default FORMAT locale.
GregorianCalendar(int year, int month, int dayOfMonth) Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute) Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second) Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
GregorianCalendar(Locale aLocale) Constructs a GregorianCalendar based on the current time in the default time zone with the given locale.
GregorianCalendar(TimeZone zone) Constructs a GregorianCalendar based on the current time in the given time zone with the default FORMAT locale.
GregorianCalendar(TimeZone zone, Locale aLocale) Constructs a GregorianCalendar based on the current time in the given time zone with the given locale.

Methods

Modifier and Type Method Description
void add(int field, int amount) Adds the specified (signed) amount of time to the given calendar field, based on the calendar’s rules.
protected void computeFields() Converts the time value (millisecond offset from the Epoch) to calendar field values.
protected void computeTime() Converts calendar field values to the time value (millisecond offset from the Epoch).
boolean equals(Object obj) Compares this GregorianCalendar to the specified Object.
static GregorianCalendar from(ZonedDateTime zdt) Obtains an instance of GregorianCalendar with the default locale from a ZonedDateTime object.
int getActualMaximum(int field) Returns the maximum value that this calendar field could have, taking into consideration the given time value and the current values of the getFirstDayOfWeek, getMinimalDaysInFirstWeek, getGregorianChange and getTimeZone methods.
int getActualMinimum(int field) Returns the minimum value that this calendar field could have, taking into consideration the given time value and the current values of the getFirstDayOfWeek, getMinimalDaysInFirstWeek, getGregorianChange and getTimeZone methods.
String getCalendarType() Returns "gregory" as the calendar type.
int getGreatestMinimum(int field) Returns the highest minimum value for the given calendar field of this GregorianCalendar instance.
Date getGregorianChange() Gets the Gregorian Calendar change date.
int getLeastMaximum(int field) Returns the lowest maximum value for the given calendar field of this GregorianCalendar instance.
int getMaximum(int field) Returns the maximum value for the given calendar field of this GregorianCalendar instance.
int getMinimum(int field) Returns the minimum value for the given calendar field of this GregorianCalendar instance.
int getWeeksInWeekYear() Returns the number of weeks in the week year represented by this GregorianCalendar.
int getWeekYear() Returns the week year represented by this GregorianCalendar.
int hashCode() Generates the hash code for this GregorianCalendar object.
boolean isLeapYear(int year) Determines if the given year is a leap year.
boolean isWeekDateSupported() Returns true indicating this GregorianCalendar supports week dates.
void roll(int field, boolean up) Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
void roll(int field, int amount) Adds a signed amount to the specified calendar field without changing larger fields.
void setGregorianChange(Date date) Sets the GregorianCalendar change date.
void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) Sets this GregorianCalendar to the date given by the date specifiers - weekYear, weekOfYear, and dayOfWeek.
ZonedDateTime toZonedDateTime() Converts this object to a ZonedDateTime that represents the same point on the time-line as this GregorianCalendar.

多态的使用场合

  1. 参数个数不同形成多态
  2. 父类指向不同子类形成多态
  3. 返回值不同形成多态

Java 8日期相关类

Java 8发布的新的处理日期时间类数据的方案:

  • package java.time:The main API for dates, times, instants, and durations.

    The classes defined here represent the principle date-time concepts, including instants, durations, dates, times, time-zones and periods. They are based on the ISO calendar system, which is the de facto world calendar following the proleptic Gregorian rules. All the classes are immutable and thread-safe.

  • package java.time.chrono:Generic API for calendar systems other than the default ISO.

    The main API is based around the calendar system defined in ISO-8601. However, there are other calendar systems, and this package provides basic support for them.

  • package java.time.format:Provides classes to print and parse dates and times.

    Printing and parsing is based around the DateTimeFormatter class. Instances are generally obtained from DateTimeFormatter, however DateTimeFormatterBuilder can be used if more power is needed.

    Localization occurs by calling withLocale(Locale) on the formatter. Further customization is possible using DecimalStyle.

  • package java.time.temporal:Access to date and time using fields and units, and date time adjusters.

    This package expands on the base package to provide additional functionality for more powerful use cases. Support is included for:

    • Units of date-time, such as years, months, days and hours
    • Fields of date-time, such as month-of-year, day-of-week or hour-of-day
    • Date-time adjustment functions
    • Different definitions of weeks
  • package java.time.zone:Support for time-zones and their rules.

    Daylight Saving Time and Time-Zones are concepts used by Governments to alter local time. This package provides support for time-zones, their rules and the resulting gaps and overlaps in the local time-line typically caused by Daylight Saving Time.

class LocalDate

public final class LocalDate
extends Object
implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable

A date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03.

This class is immutable and thread-safe.

Fields

Modifier and Type Field Description
static LocalDate EPOCH The epoch year LocalDate, ‘1970-01-01’.
static LocalDate MAX The maximum supported LocalDate, ‘+999999999-12-31’.
static LocalDate MIN The minimum supported LocalDate, ‘-999999999-01-01’.

Methods

Modifier and Type Method Description
static LocalDate now() Obtains the current date from the system clock in the default time-zone.
static LocalDate now(Clock clock) Obtains the current date from the specified clock.
static LocalDate now(ZoneId zone) Obtains the current date from the system clock in the specified time-zone.
Temporal adjustInto(Temporal temporal) Adjusts the specified temporal object to have the same date as this object.
LocalDateTime atStartOfDay() Combines this date with the time of midnight to create a LocalDateTime at the start of this date.
ZonedDateTime atStartOfDay(ZoneId zone) Returns a zoned date-time from this date at the earliest valid time according to the rules in the time-zone.
LocalDateTime atTime(int hour, int minute) Combines this date with a time to create a LocalDateTime.
LocalDateTime atTime(int hour, int minute, int second) Combines this date with a time to create a LocalDateTime.
LocalDateTime atTime(int hour, int minute, int second, int nanoOfSecond) Combines this date with a time to create a LocalDateTime.
LocalDateTime atTime(LocalTime time) Combines this date with a time to create a LocalDateTime.
OffsetDateTime atTime(OffsetTime time) Combines this date with an offset time to create an OffsetDateTime.
int compareTo(ChronoLocalDate other) Compares this date to another date.
Stream<LocalDate> datesUntil(LocalDate endExclusive) Returns a sequential ordered stream of dates.
Stream<LocalDate> datesUntil(LocalDate endExclusive, Period step) Returns a sequential ordered stream of dates by given incremental step.
boolean equals(Object obj) Checks if this date is equal to another date.
String format(DateTimeFormatter formatter) Formats this date using the specified formatter.
static LocalDate from(TemporalAccessor temporal) Obtains an instance of LocalDate from a temporal object.
int get(TemporalField field) Gets the value of the specified field from this date as an int.
IsoChronology getChronology() Gets the chronology of this date, which is the ISO calendar system.
int getDayOfMonth() Gets the day-of-month field.
DayOfWeek getDayOfWeek() Gets the day-of-week field, which is an enum DayOfWeek.
int getDayOfYear() Gets the day-of-year field.
IsoEra getEra() Gets the era applicable at this date.
long getLong(TemporalField field) Gets the value of the specified field from this date as a long.
Month getMonth() Gets the month-of-year field using the Month enum.
int getMonthValue() Gets the month-of-year field from 1 to 12.
int getYear() Gets the year field.
int hashCode() A hash code for this date.
boolean isAfter(ChronoLocalDate other) Checks if this date is after the specified date.
boolean isBefore(ChronoLocalDate other) Checks if this date is before the specified date.
boolean isEqual(ChronoLocalDate other) Checks if this date is equal to the specified date.
boolean isLeapYear() Checks if the year is a leap year, according to the ISO proleptic calendar system rules.
boolean isSupported(TemporalField field) Checks if the specified field is supported.
boolean isSupported(TemporalUnit unit) Checks if the specified unit is supported.
int lengthOfMonth() Returns the length of the month represented by this date.
int lengthOfYear() Returns the length of the year represented by this date.
LocalDate minus(long amountToSubtract, TemporalUnit unit) Returns a copy of this date with the specified amount subtracted.
LocalDate minus(TemporalAmount amountToSubtract) Returns a copy of this date with the specified amount subtracted.
LocalDate minusDays(long daysToSubtract) Returns a copy of this LocalDate with the specified number of days subtracted.
LocalDate minusMonths(long monthsToSubtract) Returns a copy of this LocalDate with the specified number of months subtracted.
LocalDate minusWeeks(long weeksToSubtract) Returns a copy of this LocalDate with the specified number of weeks subtracted.
LocalDate minusYears(long yearsToSubtract) Returns a copy of this LocalDate with the specified number of years subtracted.
static LocalDate of(int year, int month, int dayOfMonth) Obtains an instance of LocalDate from a year, month and day.
static LocalDate of(int year, Month month, int dayOfMonth) Obtains an instance of LocalDate from a year, month and day.
static LocalDate ofEpochDay(long epochDay) Obtains an instance of LocalDate from the epoch day count.
static LocalDate ofInstant(Instant instant, ZoneId zone) Obtains an instance of LocalDate from an Instant and zone ID.
static LocalDate ofYearDay(int year, int dayOfYear) Obtains an instance of LocalDate from a year and day-of-year.
static LocalDate parse(CharSequence text) Obtains an instance of LocalDate from a text string such as 2007-12-03.
static LocalDate parse(CharSequence text, DateTimeFormatter formatter) Obtains an instance of LocalDate from a text string using a specific formatter.
LocalDate plus(long amountToAdd, TemporalUnit unit) Returns a copy of this date with the specified amount added.
LocalDate plus(TemporalAmount amountToAdd) Returns a copy of this date with the specified amount added.
LocalDate plusDays(long daysToAdd) Returns a copy of this LocalDate with the specified number of days added.
LocalDate plusMonths(long monthsToAdd) Returns a copy of this LocalDate with the specified number of months added.
LocalDate plusWeeks(long weeksToAdd) Returns a copy of this LocalDate with the specified number of weeks added.
LocalDate plusYears(long yearsToAdd) Returns a copy of this LocalDate with the specified number of years added.
<R> R query(TemporalQuery<R> query) Queries this date using the specified query.
ValueRange range(TemporalField field) Gets the range of valid values for the specified field.
long toEpochSecond(LocalTime time, ZoneOffset offset) Converts this LocalDate to the number of seconds since the epoch of 1970-01-01T00:00:00Z.
String toString() Outputs this date as a String, such as 2007-12-03.
Period until(ChronoLocalDate endDateExclusive) Calculates the period between this date and another date as a Period.
long until(Temporal endExclusive, TemporalUnit unit) Calculates the amount of time until another date in terms of the specified unit.
LocalDate with(TemporalAdjuster adjuster) Returns an adjusted copy of this date.
LocalDate with(TemporalField field, long newValue) Returns a copy of this date with the specified field set to a new value.
LocalDate withDayOfMonth(int dayOfMonth) Returns a copy of this LocalDate with the day-of-month altered.
LocalDate withDayOfYear(int dayOfYear) Returns a copy of this LocalDate with the day-of-year altered.
LocalDate withMonth(int month) Returns a copy of this LocalDate with the month-of-year altered.
LocalDate withYear(int year) Returns a copy of this LocalDate with the year altered.
final LocalDate now = LocalDate.now();
System.out.println(now);

Output:

2021-07-29

Process finished with exit code 0

class LocalDateTime

public final class LocalDateTime
extends Object
implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable

A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.

LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value “2nd October 2007 at 13:45.30.123456789” can be stored in a LocalDateTime.

This class is immutable and thread-safe.

Fields

Modifier and Type Field Description
static LocalDateTime MAX The maximum supported LocalDateTime, ‘+999999999-12-31T23:59:59.999999999’.
static LocalDateTime MIN The minimum supported LocalDateTime, ‘-999999999-01-01T00:00:00’.

Methods

Modifier and Type Method Description
Temporal adjustInto(Temporal temporal) Adjusts the specified temporal object to have the same date and time as this object.
OffsetDateTime atOffset(ZoneOffset offset) Combines this date-time with an offset to create an OffsetDateTime.
ZonedDateTime atZone(ZoneId zone) Combines this date-time with a time-zone to create a ZonedDateTime.
int compareTo(ChronoLocalDateTime<?> other) Compares this date-time to another date-time.
boolean equals(Object obj) Checks if this date-time is equal to another date-time.
String format(DateTimeFormatter formatter) Formats this date-time using the specified formatter.
static LocalDateTime from(TemporalAccessor temporal) Obtains an instance of LocalDateTime from a temporal object.
int get(TemporalField field) Gets the value of the specified field from this date-time as an int.
int getDayOfMonth() Gets the day-of-month field.
DayOfWeek getDayOfWeek() Gets the day-of-week field, which is an enum DayOfWeek.
int getDayOfYear() Gets the day-of-year field.
int getHour() Gets the hour-of-day field.
long getLong(TemporalField field) Gets the value of the specified field from this date-time as a long.
int getMinute() Gets the minute-of-hour field.
Month getMonth() Gets the month-of-year field using the Month enum.
int getMonthValue() Gets the month-of-year field from 1 to 12.
int getNano() Gets the nano-of-second field.
int getSecond() Gets the second-of-minute field.
int getYear() Gets the year field.
int hashCode() A hash code for this date-time.
boolean isAfter(ChronoLocalDateTime<?> other) Checks if this date-time is after the specified date-time.
boolean isBefore(ChronoLocalDateTime<?> other) Checks if this date-time is before the specified date-time.
boolean isEqual(ChronoLocalDateTime<?> other) Checks if this date-time is equal to the specified date-time.
boolean isSupported(TemporalField field) Checks if the specified field is supported.
boolean isSupported(TemporalUnit unit) Checks if the specified unit is supported.
LocalDateTime minus(long amountToSubtract, TemporalUnit unit) Returns a copy of this date-time with the specified amount subtracted.
LocalDateTime minus(TemporalAmount amountToSubtract) Returns a copy of this date-time with the specified amount subtracted.
LocalDateTime minusDays(long days) Returns a copy of this LocalDateTime with the specified number of days subtracted.
LocalDateTime minusHours(long hours) Returns a copy of this LocalDateTime with the specified number of hours subtracted.
LocalDateTime minusMinutes(long minutes) Returns a copy of this LocalDateTime with the specified number of minutes subtracted.
LocalDateTime minusMonths(long months) Returns a copy of this LocalDateTime with the specified number of months subtracted.
LocalDateTime minusNanos(long nanos) Returns a copy of this LocalDateTime with the specified number of nanoseconds subtracted.
LocalDateTime minusSeconds(long seconds) Returns a copy of this LocalDateTime with the specified number of seconds subtracted.
LocalDateTime minusWeeks(long weeks) Returns a copy of this LocalDateTime with the specified number of weeks subtracted.
LocalDateTime minusYears(long years) Returns a copy of this LocalDateTime with the specified number of years subtracted.
static LocalDateTime now() Obtains the current date-time from the system clock in the default time-zone.
static LocalDateTime now(Clock clock) Obtains the current date-time from the specified clock.
static LocalDateTime now(ZoneId zone) Obtains the current date-time from the system clock in the specified time-zone.
static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute) Obtains an instance of LocalDateTime from year, month, day, hour and minute, setting the second and nanosecond to zero.
static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second) Obtains an instance of LocalDateTime from year, month, day, hour, minute and second, setting the nanosecond to zero.
static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) Obtains an instance of LocalDateTime from year, month, day, hour, minute, second and nanosecond.
static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute) Obtains an instance of LocalDateTime from year, month, day, hour and minute, setting the second and nanosecond to zero.
static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second) Obtains an instance of LocalDateTime from year, month, day, hour, minute and second, setting the nanosecond to zero.
static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) Obtains an instance of LocalDateTime from year, month, day, hour, minute, second and nanosecond.
static LocalDateTime of(LocalDate date, LocalTime time) Obtains an instance of LocalDateTime from a date and time.
static LocalDateTime ofEpochSecond(long epochSecond, int nanoOfSecond, ZoneOffset offset) Obtains an instance of LocalDateTime using seconds from the epoch of 1970-01-01T00:00:00Z.
static LocalDateTime ofInstant(Instant instant, ZoneId zone) Obtains an instance of LocalDateTime from an Instant and zone ID.
static LocalDateTime parse(CharSequence text) Obtains an instance of LocalDateTime from a text string such as 2007-12-03T10:15:30.
static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter) Obtains an instance of LocalDateTime from a text string using a specific formatter.
LocalDateTime plus(long amountToAdd, TemporalUnit unit) Returns a copy of this date-time with the specified amount added.
LocalDateTime plus(TemporalAmount amountToAdd) Returns a copy of this date-time with the specified amount added.
LocalDateTime plusDays(long days) Returns a copy of this LocalDateTime with the specified number of days added.
LocalDateTime plusHours(long hours) Returns a copy of this LocalDateTime with the specified number of hours added.
LocalDateTime plusMinutes(long minutes) Returns a copy of this LocalDateTime with the specified number of minutes added.
LocalDateTime plusMonths(long months) Returns a copy of this LocalDateTime with the specified number of months added.
LocalDateTime plusNanos(long nanos) Returns a copy of this LocalDateTime with the specified number of nanoseconds added.
LocalDateTime plusSeconds(long seconds) Returns a copy of this LocalDateTime with the specified number of seconds added.
LocalDateTime plusWeeks(long weeks) Returns a copy of this LocalDateTime with the specified number of weeks added.
LocalDateTime plusYears(long years) Returns a copy of this LocalDateTime with the specified number of years added.
<R> R query(TemporalQuery<R> query) Queries this date-time using the specified query.
ValueRange range(TemporalField field) Gets the range of valid values for the specified field.
LocalDate toLocalDate() Gets the LocalDate part of this date-time.
LocalTime toLocalTime() Gets the LocalTime part of this date-time.
String toString() Outputs this date-time as a String, such as 2007-12-03T10:15:30.
LocalDateTime truncatedTo(TemporalUnit unit) Returns a copy of this LocalDateTime with the time truncated.
long until(Temporal endExclusive, TemporalUnit unit) Calculates the amount of time until another date-time in terms of the specified unit.
LocalDateTime with(TemporalAdjuster adjuster) Returns an adjusted copy of this date-time.
LocalDateTime with(TemporalField field, long newValue) Returns a copy of this date-time with the specified field set to a new value.
LocalDateTime withDayOfMonth(int dayOfMonth) Returns a copy of this LocalDateTime with the day-of-month altered.
LocalDateTime withDayOfYear(int dayOfYear) Returns a copy of this LocalDateTime with the day-of-year altered.
LocalDateTime withHour(int hour) Returns a copy of this LocalDateTime with the hour-of-day altered.
LocalDateTime withMinute(int minute) Returns a copy of this LocalDateTime with the minute-of-hour altered.
LocalDateTime withMonth(int month) Returns a copy of this LocalDateTime with the month-of-year altered.
LocalDateTime withNano(int nanoOfSecond) Returns a copy of this LocalDateTime with the nano-of-second altered.
LocalDateTime withSecond(int second) Returns a copy of this LocalDateTime with the second-of-minute altered.
LocalDateTime withYear(int year) Returns a copy of this LocalDateTime with the year altered.
final LocalDateTime now = LocalDateTime.now();
System.out.println(now);
final LocalDateTime dt = LocalDateTime.of(2021, 7, 29, 10, 53);
System.out.println(dt);

Output:

2021-07-29T22:47:08.724731600

2021-07-29T10:53

Process finished with exit code 0

class Instant

public final class Instant
extends Object
implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable

An instantaneous point on the time-line. This class models a single instantaneous point on the time-line. This might be used to record event time-stamps in the application.

This class is immutable and thread-safe.

Fields

Modifier and Type Field Description
static Instant EPOCH Constant for the 1970-01-01T00:00:00Z epoch instant.
static Instant MAX The maximum supported Instant, ‘1000000000-12-31T23:59:59.999999999Z’.
static Instant MIN The minimum supported Instant, ‘-1000000000-01-01T00:00Z’.

Methods

Modifier and Type Method Description
Temporal adjustInto(Temporal temporal) Adjusts the specified temporal object to have this instant.
OffsetDateTime atOffset(ZoneOffset offset) Combines this instant with an offset to create an OffsetDateTime.
ZonedDateTime atZone(ZoneId zone) Combines this instant with a time-zone to create a ZonedDateTime.
int compareTo(Instant otherInstant) Compares this instant to the specified instant.
boolean equals(Object otherInstant) Checks if this instant is equal to the specified instant.
static Instant from(TemporalAccessor temporal) Obtains an instance of Instant from a temporal object.
int get(TemporalField field) Gets the value of the specified field from this instant as an int.
long getEpochSecond() Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z.
long getLong(TemporalField field) Gets the value of the specified field from this instant as a long.
int getNano() Gets the number of nanoseconds, later along the time-line, from the start of the second.
int hashCode() Returns a hash code for this instant.
boolean isAfter(Instant otherInstant) Checks if this instant is after the specified instant.
boolean isBefore(Instant otherInstant) Checks if this instant is before the specified instant.
boolean isSupported(TemporalField field) Checks if the specified field is supported.
boolean isSupported(TemporalUnit unit) Checks if the specified unit is supported.
Instant minus(long amountToSubtract, TemporalUnit unit) Returns a copy of this instant with the specified amount subtracted.
Instant minus(TemporalAmount amountToSubtract) Returns a copy of this instant with the specified amount subtracted.
Instant minusMillis(long millisToSubtract) Returns a copy of this instant with the specified duration in milliseconds subtracted.
Instant minusNanos(long nanosToSubtract) Returns a copy of this instant with the specified duration in nanoseconds subtracted.
Instant minusSeconds(long secondsToSubtract) Returns a copy of this instant with the specified duration in seconds subtracted.
static Instant now() Obtains the current instant from the system clock (UTC 0).
static Instant now(Clock clock) Obtains the current instant from the specified clock.
static Instant ofEpochMilli(long epochMilli) Obtains an instance of Instant using milliseconds from the epoch of 1970-01-01T00:00:00Z.
static Instant ofEpochSecond(long epochSecond) Obtains an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z.
static Instant ofEpochSecond(long epochSecond, long nanoAdjustment) Obtains an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second.
static Instant parse(CharSequence text) Obtains an instance of Instant from a text string such as 2007-12-03T10:15:30.00Z.
Instant plus(long amountToAdd, TemporalUnit unit) Returns a copy of this instant with the specified amount added.
Instant plus(TemporalAmount amountToAdd) Returns a copy of this instant with the specified amount added.
Instant plusMillis(long millisToAdd) Returns a copy of this instant with the specified duration in milliseconds added.
Instant plusNanos(long nanosToAdd) Returns a copy of this instant with the specified duration in nanoseconds added.
Instant plusSeconds(long secondsToAdd) Returns a copy of this instant with the specified duration in seconds added.
<R> R query(TemporalQuery<R> query) Queries this instant using the specified query.
ValueRange range(TemporalField field) Gets the range of valid values for the specified field.
long toEpochMilli() Converts this instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z.
String toString() A string representation of this instant using ISO-8601 representation.
Instant truncatedTo(TemporalUnit unit) Returns a copy of this Instant truncated to the specified unit.
long until(Temporal endExclusive, TemporalUnit unit) Calculates the amount of time until another instant in terms of the specified unit.
Instant with(TemporalAdjuster adjuster) Returns an adjusted copy of this instant.
Instant with(TemporalField field, long newValue) Returns a copy of this instant with the specified field set to a new value.
final OffsetDateTime offsetDateTime = Instant.now().atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);

Output:

2021-07-29T23:13:17.997944800+08:00

Process finished with exit code 0

class DateTimeFormatter

public final class DateTimeFormatter
extends Object

Formatter for printing and parsing date-time objects.

This class provides the main application entry point for printing and parsing and provides common implementations of DateTimeFormatter:

  • Using predefined constants, such as ISO_LOCAL_DATE
  • Using pattern letters, such as uuuu-MMM-dd
  • Using localized styles, such as long or medium

More complex formatters are provided by DateTimeFormatterBuilder.

Predefined Formatters

Formatter Description Example
ofLocalizedDate(dateStyle) Formatter with date style from the locale ‘2011-12-03’
ofLocalizedTime(timeStyle) Formatter with time style from the locale ‘10:15:30’
ofLocalizedDateTime(dateTimeStyle) Formatter with a style for date and time from the locale ‘3 Jun 2008 11:05:30’
ofLocalizedDateTime(dateStyle,timeStyle) Formatter with date and time styles from the locale ‘3 Jun 2008 11:05’
BASIC_ISO_DATE Basic ISO date ‘20111203’
ISO_LOCAL_DATE ISO Local Date ‘2011-12-03’
ISO_OFFSET_DATE ISO Date with offset ‘2011-12-03+01:00’
ISO_DATE ISO Date with or without offset ‘2011-12-03+01:00’; ‘2011-12-03’
ISO_LOCAL_TIME Time without offset ‘10:15:30’
ISO_OFFSET_TIME Time with offset ‘10:15:30+01:00’
ISO_TIME Time with or without offset ‘10:15:30+01:00’; ‘10:15:30’
ISO_LOCAL_DATE_TIME ISO Local Date and Time ‘2011-12-03T10:15:30’
ISO_OFFSET_DATE_TIME Date Time with Offset ‘2011-12-03T10:15:30+01:00’
ISO_ZONED_DATE_TIME Zoned Date Time ‘2011-12-03T10:15:30+01:00[Europe/Paris]’
ISO_DATE_TIME Date and time with ZoneId ‘2011-12-03T10:15:30+01:00[Europe/Paris]’
ISO_ORDINAL_DATE Year and day of year ‘2012-337’
ISO_WEEK_DATE Year and Week ‘2012-W48-6’
ISO_INSTANT Date and Time of an Instant ‘2011-12-03T10:15:30Z’
RFC_1123_DATE_TIME RFC 1123 / RFC 822 ‘Tue, 3 Jun 2008 11:05:30 GMT’

Pattern Letters and Symbols

Symbol Meaning Presentation Examples
G era text AD; Anno Domini; A
u year year 2004; 04
y year-of-era year 2004; 04
D day-of-year number 189
M/L month-of-year number/text 7; 07; Jul; July; J
d day-of-month number 10
g modified-julian-day number 2451334
Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter
Y week-based-year year 1996; 96
w week-of-week-based-year number 27
W week-of-month number 4
E day-of-week text Tue; Tuesday; T
e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T
F day-of-week-in-month number 3
a am-pm-of-day text PM
h clock-hour-of-am-pm (1-12) number 12
K hour-of-am-pm (0-11) number 0
k clock-hour-of-day (1-24) number 24
H hour-of-day (0-23) number 0
m minute-of-hour number 30
s second-of-minute number 55
S fraction-of-second fraction 978
A milli-of-day number 1234
n nano-of-second number 987654321
N nano-of-day number 1234000000
V time-zone ID zone-id America/Los_Angeles; Z; -08:30
v generic time-zone name zone-name Pacific Time; PT
z time-zone name zone-name Pacific Standard Time; PST
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00
X zone-offset ‘Z’ for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15
Z zone-offset offset-Z +0000; -0800; -08:00
p pad next pad modifier 1
escape for text delimiter
‘’ single quote literal
[ optional section start
] optional section end
# reserved for future use
{ reserved for future use
} reserved for future use

The count of pattern letters determines the format.

Fields

Modifier and Type Field Description
static DateTimeFormatter BASIC_ISO_DATE The ISO date formatter that formats or parses a date without an offset, such as ‘20111203’.
static DateTimeFormatter ISO_DATE The ISO date formatter that formats or parses a date with the offset if available, such as ‘2011-12-03’ or ‘2011-12-03+01:00’.
static DateTimeFormatter ISO_DATE_TIME The ISO-like date-time formatter that formats or parses a date-time with the offset and zone if available, such as ‘2011-12-03T10:15:30’, ‘2011-12-03T10:15:30+01:00’ or ‘2011-12-03T10:15:30+01:00[Europe/Paris]’.
static DateTimeFormatter ISO_INSTANT The ISO instant formatter that formats or parses an instant in UTC, such as ‘2011-12-03T10:15:30Z’.
static DateTimeFormatter ISO_LOCAL_DATE The ISO date formatter that formats or parses a date without an offset, such as ‘2011-12-03’.
static DateTimeFormatter ISO_LOCAL_DATE_TIME The ISO date-time formatter that formats or parses a date-time without an offset, such as ‘2011-12-03T10:15:30’.
static DateTimeFormatter ISO_LOCAL_TIME The ISO time formatter that formats or parses a time without an offset, such as ‘10:15’ or ‘10:15:30’.
static DateTimeFormatter ISO_OFFSET_DATE The ISO date formatter that formats or parses a date with an offset, such as ‘2011-12-03+01:00’.
static DateTimeFormatter ISO_OFFSET_DATE_TIME The ISO date-time formatter that formats or parses a date-time with an offset, such as ‘2011-12-03T10:15:30+01:00’.
static DateTimeFormatter ISO_OFFSET_TIME The ISO time formatter that formats or parses a time with an offset, such as ‘10:15+01:00’ or ‘10:15:30+01:00’.
static DateTimeFormatter ISO_ORDINAL_DATE The ISO date formatter that formats or parses the ordinal date without an offset, such as ‘2012-337’.
static DateTimeFormatter ISO_TIME The ISO time formatter that formats or parses a time, with the offset if available, such as ‘10:15’, ‘10:15:30’ or ‘10:15:30+01:00’.
static DateTimeFormatter ISO_WEEK_DATE The ISO date formatter that formats or parses the week-based date without an offset, such as ‘2012-W48-6’.
static DateTimeFormatter ISO_ZONED_DATE_TIME The ISO-like date-time formatter that formats or parses a date-time with offset and zone, such as ‘2011-12-03T10:15:30+01:00[Europe/Paris]’.
static DateTimeFormatter RFC_1123_DATE_TIME The RFC-1123 date-time formatter, such as ‘Tue, 3 Jun 2008 11:05:30 GMT’.

Methods

Modifier and Type Method Description
String format(TemporalAccessor temporal) Formats a date-time object using this formatter.
void formatTo(TemporalAccessor temporal, Appendable appendable) Formats a date-time object to an Appendable using this formatter.
Chronology getChronology() Gets the overriding chronology to be used during formatting.
DecimalStyle getDecimalStyle() Gets the DecimalStyle to be used during formatting.
Locale getLocale() Gets the locale to be used during formatting.
Set<TemporalField> getResolverFields() Gets the resolver fields to use during parsing.
ResolverStyle getResolverStyle() Gets the resolver style to use during parsing.
ZoneId getZone() Gets the overriding zone to be used during formatting.
DateTimeFormatter localizedBy(Locale locale) Returns a copy of this formatter with localized values of the locale, calendar, region, decimal style and/or timezone, that supercede values in this formatter.
static DateTimeFormatter ofLocalizedDate(FormatStyle dateStyle) Returns a locale specific date format for the ISO chronology.
static DateTimeFormatter ofLocalizedDateTime(FormatStyle dateTimeStyle) Returns a locale specific date-time formatter for the ISO chronology.
static DateTimeFormatter ofLocalizedDateTime(FormatStyle dateStyle, FormatStyle timeStyle) Returns a locale specific date and time format for the ISO chronology.
static DateTimeFormatter ofLocalizedTime(FormatStyle timeStyle) Returns a locale specific time format for the ISO chronology.
static DateTimeFormatter ofPattern(String pattern) Creates a formatter using the specified pattern.
static DateTimeFormatter ofPattern(String pattern, Locale locale) Creates a formatter using the specified pattern and locale.
TemporalAccessor parse(CharSequence text) Fully parses the text producing a temporal object.
TemporalAccessor parse(CharSequence text, ParsePosition position) Parses the text using this formatter, providing control over the text position.
<T> T parse(CharSequence text, TemporalQuery<T> query) Fully parses the text producing an object of the specified type.
TemporalAccessor parseBest(CharSequence text, TemporalQuery<?>... queries) Fully parses the text producing an object of one of the specified types.
static TemporalQuery<Period> parsedExcessDays() A query that provides access to the excess days that were parsed.
static TemporalQuery<Boolean> parsedLeapSecond() A query that provides access to whether a leap-second was parsed.
TemporalAccessor parseUnresolved(CharSequence text, ParsePosition position) Parses the text using this formatter, without resolving the result, intended for advanced use cases.
Format toFormat() Returns this formatter as a java.text.Format instance.
Format toFormat(TemporalQuery<?> parseQuery) Returns this formatter as a java.text.Format instance that will parse using the specified query.
String toString() Returns a description of the underlying formatters.
DateTimeFormatter withChronology(Chronology chrono) Returns a copy of this formatter with a new override chronology.
DateTimeFormatter withDecimalStyle(DecimalStyle decimalStyle) Returns a copy of this formatter with a new DecimalStyle.
DateTimeFormatter withLocale(Locale locale) Returns a copy of this formatter with a new locale.
DateTimeFormatter withResolverFields(TemporalField... resolverFields) Returns a copy of this formatter with a new set of resolver fields.
DateTimeFormatter withResolverFields(Set<TemporalField> resolverFields) Returns a copy of this formatter with a new set of resolver fields.
DateTimeFormatter withResolverStyle(ResolverStyle resolverStyle) Returns a copy of this formatter with a new resolver style.
DateTimeFormatter withZone(ZoneId zone) Returns a copy of this formatter with a new override zone.

enum FormatStyle

public enum FormatStyle
extends Enum<FormatStyle>

Enumeration of the style of a localized date, time or date-time formatter.

This is an immutable and thread-safe enum.

Enum Constants

Enum Constant Description
FULL Full text style, with the most detail.
LONG Long text style, with lots of detail.
MEDIUM Medium text style, with some detail.
SHORT Short text style, typically numeric.

class Locale

public final class Locale
extends Object
implements Cloneable, Serializable

A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation— the number should be formatted according to the customs and conventions of the user’s native country, region, or culture.

Nested classes

Modifier and Type Class Description
static class Locale.Builder Builder is used to build instances of Locale from values configured by the setters.
static class Locale.Category Enum for locale categories.
static class Locale.FilteringMode This enum provides constants to select a filtering mode for locale matching.
static class Locale.IsoCountryCode Enum for specifying the type defined in ISO 3166.
static class Locale.LanguageRange This class expresses a Language Range defined in RFC 4647 Matching of Language Tags.

Fields

Modifier and Type Field Description
static Locale CANADA Useful constant for country.
static Locale CANADA_FRENCH Useful constant for country.
static Locale CHINA Useful constant for country.
static Locale CHINESE Useful constant for language.
static Locale ENGLISH Useful constant for language.
static Locale FRANCE Useful constant for country.
static Locale FRENCH Useful constant for language.
static Locale GERMAN Useful constant for language.
static Locale GERMANY Useful constant for country.
static Locale ITALIAN Useful constant for language.
static Locale ITALY Useful constant for country.
static Locale JAPAN Useful constant for country.
static Locale JAPANESE Useful constant for language.
static Locale KOREA Useful constant for country.
static Locale KOREAN Useful constant for language.
static Locale PRC Useful constant for country.
static char PRIVATE_USE_EXTENSION The key for the private use extension (‘x’).
static Locale ROOT Useful constant for the root locale.
static Locale SIMPLIFIED_CHINESE Useful constant for language.
static Locale TAIWAN Useful constant for country.
static Locale TRADITIONAL_CHINESE Useful constant for language.
static Locale UK Useful constant for country.
static char UNICODE_LOCALE_EXTENSION The key for Unicode locale extension (‘u’).
static Locale US Useful constant for country.

Constructors

Constructor Description
Locale(String language) Construct a locale from a language code.
Locale(String language, String country) Construct a locale from language and country.
Locale(String language, String country, String variant) Construct a locale from language, country and variant.

Methods

Modifier and Type Method Description
Object clone() Overrides Cloneable.
boolean equals(Object obj) Returns true if this Locale is equal to another object.
static List<Locale> filter(List<Locale.LanguageRange> priorityList, Collection<Locale> locales) Returns a list of matching Locale instances using the filtering mechanism defined in RFC 4647.
static List<Locale> filter(List<Locale.LanguageRange> priorityList, Collection<Locale> locales, Locale.FilteringMode mode) Returns a list of matching Locale instances using the filtering mechanism defined in RFC 4647.
static List<String> filterTags(List<Locale.LanguageRange> priorityList, Collection<String> tags) Returns a list of matching languages tags using the basic filtering mechanism defined in RFC 4647.
static List<String> filterTags(List<Locale.LanguageRange> priorityList, Collection<String> tags, Locale.FilteringMode mode) Returns a list of matching languages tags using the basic filtering mechanism defined in RFC 4647.
static Locale forLanguageTag(String languageTag) Returns a locale for the specified IETF BCP 47 language tag string.
static Locale[] getAvailableLocales() Returns an array of all installed locales.
String getCountry() Returns the country/region code for this locale, which should either be the empty string, an uppercase ISO 3166 2-letter code, or a UN M.49 3-digit code.
static Locale getDefault() Gets the current value of the default locale for this instance of the Java Virtual Machine.
static Locale getDefault(Locale.Category category) Gets the current value of the default locale for the specified Category for this instance of the Java Virtual Machine.
String getDisplayCountry() Returns a name for the locale’s country that is appropriate for display to the user.
String getDisplayCountry(Locale inLocale) Returns a name for the locale’s country that is appropriate for display to the user.
String getDisplayLanguage() Returns a name for the locale’s language that is appropriate for display to the user.
String getDisplayLanguage(Locale inLocale) Returns a name for the locale’s language that is appropriate for display to the user.
String getDisplayName() Returns a name for the locale that is appropriate for display to the user.
String getDisplayName(Locale inLocale) Returns a name for the locale that is appropriate for display to the user.
String getDisplayScript() Returns a name for the locale’s script that is appropriate for display to the user.
String getDisplayScript(Locale inLocale) Returns a name for the locale’s script that is appropriate for display to the user.
String getDisplayVariant() Returns a name for the locale’s variant code that is appropriate for display to the user.
String getDisplayVariant(Locale inLocale) Returns a name for the locale’s variant code that is appropriate for display to the user.
String getExtension(char key) Returns the extension (or private use) value associated with the specified key, or null if there is no extension associated with the key.
Set<Character> getExtensionKeys() Returns the set of extension keys associated with this locale, or the empty set if it has no extensions.
String getISO3Country() Returns a three-letter abbreviation for this locale’s country.
String getISO3Language() Returns a three-letter abbreviation of this locale’s language.
static String[] getISOCountries() Returns a list of all 2-letter country codes defined in ISO 3166.
static Set<String> getISOCountries(Locale.IsoCountryCode type) Returns a Set of ISO3166 country codes for the specified type.
static String[] getISOLanguages() Returns a list of all 2-letter language codes defined in ISO 639.
String getLanguage() Returns the language code of this Locale.
String getScript() Returns the script for this locale, which should either be the empty string or an ISO 15924 4-letter script code.
Set<String> getUnicodeLocaleAttributes() Returns the set of unicode locale attributes associated with this locale, or the empty set if it has no attributes.
Set<String> getUnicodeLocaleKeys() Returns the set of Unicode locale keys defined by this locale, or the empty set if this locale has none.
String getUnicodeLocaleType(String key) Returns the Unicode locale type associated with the specified Unicode locale key for this locale.
String getVariant() Returns the variant code for this locale.
boolean hasExtensions() Returns true if this Locale has any extensions.
int hashCode() Override hashCode.
static Locale lookup(List<Locale.LanguageRange> priorityList, Collection<Locale> locales) Returns a Locale instance for the best-matching language tag using the lookup mechanism defined in RFC 4647.
static String lookupTag(List<Locale.LanguageRange> priorityList, Collection<String> tags) Returns the best-matching language tag using the lookup mechanism defined in RFC 4647.
static void setDefault(Locale newLocale) Sets the default locale for this instance of the Java Virtual Machine.
static void setDefault(Locale.Category category, Locale newLocale) Sets the default locale for the specified Category for this instance of the Java Virtual Machine.
Locale stripExtensions() Returns a copy of this Locale with no extensions.
String toLanguageTag() Returns a well-formed IETF BCP 47 language tag representing this locale.
String toString() Returns a string representation of this Locale object, consisting of language, country, variant, script, and extensions as below: language + “" + country + "” + (variant + “#" | “#”) + script + "” + extensions Language is always lower case, country is always upper case, script is always title case, and extensions are always lower case.

Java核心类库(上)相关推荐

  1. Java 核心类库一览

    作者:白色蜗牛 来源:蜗牛互联网 阅读本文你将收获: 类库与 JAR 文件 什么是类库 我们知道,在面向对象的程序设计里,一个类是可以调用另外一个类的方法,只要把被调用的那个类引入到 classpat ...

  2. Java核心类库篇8——网络编程

    Java核心类库篇8--网络编程 1.七层网络模型 OSI(Open System Interconnect),即开放式系统互联,是ISO(国际标准化组织)组织在1985 年研究的网络互连模型. 当发 ...

  3. Java核心类库篇7——多线程

    Java核心类库篇7--多线程 1.程序.进程和线程 程序 - 数据结构 + 算法,主要指存放在硬盘上的可执行文件 进程 - 主要指运行在内存中的可执行文件 线程就是进程内部的程序流 操作系统内部支持 ...

  4. Java核心类库篇3——util

    Java核心类库篇3--util 1.Date 用于描述特定的瞬间,也就是年月日时分秒,可以精确到毫秒 1.1.构造方法 方法声明 功能介绍 public Date() 获取当前时间表示的date对象 ...

  5. Java学习笔记 - 4 Java核心类库

    4 Java 核心类库 4.1 泛型 泛型,即"参数化类型".就是将原来具体的类型参数化,类似于方法中的变量参数,此时类型也定义成参数形式(可以称之为类型形参),然后在使用/调用时 ...

  6. 第四章Java核心类库_多线程

    第四章第五节Java核心类库_多线程 多线程 一.线程与进程 1.线程与进程 2.线程调度 二.同步与异步&并发与并行 1. 同步与异步 2. 并发与并行 三.继承Thread 1.代码块 2 ...

  7. Java核心类库(下)

    文章目录 Java核心类库(下) 异常机制(重点) 基本概念 异常的分类 异常的避免 异常的捕获 异常的抛出 自定义异常 异常机制总结 File类(重点) 基本概念 常用的方法 IO流 IO流的概念 ...

  8. Java核心类库篇6——IO

    Java核心类库篇6--IO 1.File 1.1.构造方法 方法声明 功能介绍 public File(File parent, String child) 从父抽象路径名和子路径名字符串创建新的 ...

  9. Java核心类库篇5——异常

    Java核心类库篇5--异常 java.lang.Throwable类是Java语言中错误(Error)和异常(Exception)的超类 其中Error类主要用于描述Java虚拟机无法解决的严重错误 ...

最新文章

  1. Linux学习(1)-Linux几个基础命令及文件系统功能和作用
  2. 一个时代的结束:微软盖茨的人生掠影(组图)
  3. [BX] 和 loop 指令---汇编学习笔记
  4. 双目标帕累托优化_多目标稳健性决策规划(MORDM)
  5. 探索PCIe 3.0峰值性能,长江存储推新消费级固态硬盘致态TiPlus5000
  6. CANape中使用vCDMStudio批量标定
  7. Jmeter接口性能测试分布式的环境搭建
  8. 百度翻译API接口的使用
  9. 硬件工程师的真实前途我说出来可能你们不信
  10. java 关键字 assert的学习
  11. 计算机网络实验一:网线制作
  12. 学习挖掘机和程序员哪个好
  13. Css3模拟彩色灯光
  14. 获取指定日期的月份的第几个星期几是几号
  15. c语言:求正方体的表面积和体积
  16. CCNP学多长时间就行了?
  17. Python 中5种下划线的含义都是什么?
  18. 【Python实例学习】用户输入两个数字,并计算两个数字之和
  19. linux怎么安装echo命令,如何在Linux上使用Echo命令 | MOS86
  20. 点击iPhone/iPad上的加密相册或保险箱提示“无法安装加密相册或保险箱,App Store已不提供此应用”解决方案

热门文章

  1. 【电脑办公软件】万彩办公大师教程丨PDF批量添加页码工具帮助文档
  2. 真二次元!动漫形象风格迁移
  3. android学习网址
  4. 邓应海:核心PCE与鲍威尔讲话来袭,最新黄金走势分析
  5. 对比java和python对比
  6. 软件设计实验三 结构型设计模式实验
  7. libtool should recreate aclocalm4
  8. 2022年4月26日华为OD机试记录
  9. php实现贴吧功能,贴吧/盖楼的技术实现(PHP)
  10. 祛湿颗粒教你如何快速分辨与治疗湿邪