Java核心类库(上)

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 TypeMethodDescription
protected Objectclone()Creates and returns a copy of this object.
booleanequals(Object obj)Indicates whether some other object is “equal to” this one.
protected voidfinalize()Deprecated. The finalization mechanism is inherently problematic.
Class<?>getClass()Returns the runtime class of this Object.
inthashCode()Returns a hash code value for the object.
voidnotify()Wakes up a single thread that is waiting on this object’s monitor.
voidnotifyAll()Wakes up all threads that are waiting on this object’s monitor.
StringtoString()Returns a string representation of the object.
voidwait()Causes the current thread to wait until it is awakened, typically by being notified or interrupted.
voidwait(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.
voidwait(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;
    }

    @Override
    public 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);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

包装类

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

包装类对应的基本类型
java.lang.Bytebyte
java.lang.Shortshort
java.lang.Integerint
java.lang.Longlong
java.lang.Floatfloat
java.lang.Doubledouble
java.lang.Booleanboolean
java.lang.Characterchar

装箱(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

All Implemented Interfaces:

Serializable, Comparable<Integer>

public final class Integer
extends Number
implements Comparable<Integer>

常用常量

Modifier and TypeFieldDescription
static intBYTESThe number of bytes used to represent an int value in two’s complement binary form.
static intMAX_VALUEA constant holding the maximum value an int can have, 231-1.
static intMIN_VALUEA constant holding the minimum value an int can have, -231.
static intSIZEThe number of bits used to represent an int value in two’s complement binary form.
static Class<Integer>TYPEThe Class instance representing the primitive type int.

常用方法

Modifier and TypeMethodDescription
intintValue()Returns the value of this Integer as an int.
longlongValue()Returns the value of this Integer as a long after a widening primitive conversion.
booleanequals(Object obj)Compares this object to the specified object.
StringtoString()Returns a String object representing this Integer's value.
static IntegervalueOf(int i)Returns an Integer instance representing the specified int value.
static intbitCount(int i)Returns the number of one-bits in the two’s complement binary representation of the specified int value.
static IntegervalueOf(String s)Returns an Integer object holding the value of the specified String.
static IntegervalueOf(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 intparseInt(String s)Parses the string argument as a signed decimal integer.
static StringtoBinaryString(int i)Returns a string representation of the integer argument as an unsigned integer in base 2.
static StringtoHexString(int i)Returns a string representation of the integer argument as an unsigned integer in base 16.
static StringtoOctalString(int i)Returns a string representation of the integer argument as an unsigned integer in base 8.

Double

All Implemented Interfaces:

Serializable, Comparable<Integer>

public final class Double
extends Number
implements Comparable<Double>

常用常量

Modifier and TypeFieldDescription
static intBYTESThe number of bytes used to represent a double value.
static intMAX_EXPONENTMaximum exponent a finite double variable may have.
static doubleMAX_VALUEA constant holding the largest positive finite value of type double, (2-2-52)·21023.
static intMIN_EXPONENTMinimum exponent a normalized double variable may have.
static doubleMIN_NORMALA constant holding the smallest positive normal value of type double, 2-1022.
static doubleMIN_VALUEA constant holding the smallest positive nonzero value of type double, 2-1074.
static doubleNaNA constant holding a Not-a-Number (NaN) value of type double.
static doubleNEGATIVE_INFINITYA constant holding the negative infinity of type double.
static doublePOSITIVE_INFINITYA constant holding the positive infinity of type double.
static intSIZEThe number of bits used to represent a double value.
static Class<Double>TYPEThe Class instance representing the primitive type double.

常用方法

Modifier and TypeMethodDescription
bytebyteValue()Returns the value of this Double as a byte after a narrowing primitive conversion.
doubledoubleValue()Returns the double value of this Double object.
booleanequals(Object obj)Compares this object against the specified object.
StringtoString()Returns a string representation of this Double object.
booleanisNaN()Returns true if this Double value is a Not-a-Number (NaN), false otherwise.
static DoublevalueOf(double d)Returns a Double instance representing the specified double value.
static DoublevalueOf(String s)Returns a Double object holding the double value represented by the argument string s.
static doubleparseDouble(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 TypeFieldDescription
static BooleanFALSEThe Boolean object corresponding to the primitive value false.
static BooleanTRUEThe Boolean object corresponding to the primitive value true.
static Class<Boolean>TYPEThe Class object representing the primitive type boolean.

常用方法

Modifier and TypeMethodDescription
booleanbooleanValue()Returns the value of this Boolean object as a boolean primitive.
booleanequals(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.
StringtoString()Returns a String object representing this Boolean’s value.
static BooleanvalueOf(boolean b)Returns a Boolean instance representing the specified boolean value.
static BooleanvalueOf(String s)Returns a Boolean with a value represented by the specified string.
static booleanparseBoolean(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 TypeFieldDescription
static intBYTESThe number of bytes used to represent a char value in unsigned binary form.
static intSIZEThe number of bits used to represent a char value in unsigned binary form, constant 16.
static Class<Character>TYPEThe Class instance representing the primitive type char.

常用方法

Modifier and TypeMethodDescription
charcharValue()Returns the value of this Character object.
booleanequals(Object obj)Compares this object against the specified object.
StringtoString()Returns a String object representing this Character's value.
static CharactervalueOf(char c)Returns a Character instance representing the specified char value.
static booleanisUpperCase(char ch)Determines if the specified character is an uppercase character.
static booleanisLowerCase(char ch)Determines if the specified character is a lowercase character.
static booleanisWhitespace(char ch)Determines if the specified character is white space according to Java.
static booleanisDigit(char ch)Determines if the specified character is a digit.
static booleanisAlphabetic(int codePoint)Determines if the specified character (Unicode code point) is an alphabet.
static chartoUpperCase(char ch)Converts the character argument to uppercase using case mapping information from the UnicodeData file.
static chartoLowerCase(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 TypeMethodDescription
static doubleabs(double a)Returns the absolute value of a double value.
static floatabs(float a)Returns the absolute value of a float value.
static intabs(int a)Returns the absolute value of an int value.
static longabs(long a)Returns the absolute value of a long value.
static doublemax(double a, double b)Returns the greater of two double values.
static floatmax(float a, float b)Returns the greater of two float values.
static intmax(int a, int b)Returns the greater of two int values.
static longmax(long a, long b)Returns the greater of two long values.
static doublemin(double a, double b)Returns the smaller of two double values.
static floatmin(float a, float b)Returns the smaller of two float values.
static intmin(int a, int b)Returns the smaller of two int values.
static longmin(long a, long b)Returns the smaller of two long values.
static doublepow(double a, double b)Returns the value of the first argument raised to the power of the second argument.
static doublerandom()Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
static doublesqrt(double a)Returns the correctly rounded positive square root of a double value.
static longround(double a)Returns the closest long to the argument, with ties rounding to positive infinity.
static intround(float a)Returns the closest int to the argument, with ties rounding to positive infinity.

BigDecimal

实现浮点数的精确计算

All Implemented Interfaces:

Serializable, Comparable<Integer>

public class BigDecimal
extends Number
implements Comparable<BigDecimal>

常用变量

Modifier and TypeFieldDescription
static BigDecimalONEThe value 1, with a scale of 0.
static intROUND_CEILING**Deprecated.**Use RoundingMode.CEILING instead.
static intROUND_DOWN**Deprecated.**Use RoundingMode.DOWN instead.
static intROUND_FLOOR**Deprecated.**Use RoundingMode.FLOOR instead.
static intROUND_HALF_DOWN**Deprecated.**Use RoundingMode.HALF_DOWN instead.
static intROUND_HALF_EVEN**Deprecated.**Use RoundingMode.HALF_EVEN instead.
static intROUND_HALF_UP**Deprecated.**Use RoundingMode.HALF_UP instead.
static intROUND_UNNECESSARY**Deprecated.**Use RoundingMode.UNNECESSARY instead.
static intROUND_UP**Deprecated.**Use RoundingMode.UP instead.
static BigDecimalTENThe value 10, with a scale of 0.
static BigDecimalZEROThe value 0, with a scale of 0.

构造方法

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

常用方法

Modifier and TypeMethodDescription
BigDecimalabs()Returns a BigDecimal whose value is the absolute value of this BigDecimal, and whose scale is this.scale().
BigDecimaladd(BigDecimal augend)Returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(), augend.scale()).
BigDecimalsubtract(BigDecimal subtrahend)Returns a BigDecimal whose value is (this - subtrahend), and whose scale is max(this.scale(), subtrahend.scale()).
BigDecimalmultiply(BigDecimal multiplicand)Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).
BigDecimaldivide(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.
BigDecimalpow(int n)Returns a BigDecimal whose value is (thisn), The power is computed exactly, to unlimited precision.

BigInteger

表示比long更大的整数范围

All Implemented Interfaces:

Serializable, Comparable<Integer>

public class BigInteger
extends Number
implements Comparable<BigInteger>

常量

Modifier and TypeFieldDescription
static BigIntegerONEThe BigInteger constant one.
static BigIntegerTENThe BigInteger constant ten.
static BigIntegerTWOThe BigInteger constant two.
static BigIntegerZEROThe BigInteger constant zero.

构造方法

ConstructorDescription
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 TypeMethodDescription
BigIntegerabs()Returns a BigInteger whose value is the absolute value of this BigInteger.
BigIntegeradd(BigInteger val)Returns a BigInteger whose value is (this + val).
BigIntegersubtract(BigInteger val)Returns a BigInteger whose value is (this - val).
BigIntegermultiply(BigInteger val)Returns a BigInteger whose value is (this * val).
BigIntegerdivide(BigInteger val)Returns a BigInteger whose value is (this / val).
BigIntegerremainder(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

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

构造方法

ConstructorDescription
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 TypeMethodDescription
charcharAt(int index)Returns the char value at the specified index.
intlength()Returns the length of this string.
booleanisBlank()Returns true if the string is empty or contains only white space codepoints, otherwise false.
booleanisEmpty()Returns true if, and only if, length() is 0.
intcompareTo(String anotherString)Compares two strings lexicographically.
intcompareToIgnoreCase(String str)Compares two strings lexicographically, ignoring case differences.
Stringconcat(String str)Concatenates the specified string to the end of this string.
booleancontains(CharSequence s)Returns true if and only if this string contains the specified sequence of char values.
StringtoLowerCase()Converts all of the characters in this String to lower case using the rules of the default locale.
StringtoUpperCase()Converts all of the characters in this String to upper case using the rules of the default locale.
Stringtrim()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).
booleanstartsWith(String prefix)Tests if this string starts with the specified prefix.
booleanstartsWith(String prefix, int toffset)Tests if the substring of this string beginning at the specified index starts with the specified prefix.
booleanendsWith(String suffix)Tests if this string ends with the specified suffix.
booleanequals(Object anObject)Compares this string to the specified object.
booleanequalsIgnoreCase(String anotherString)Compares this String to another String, ignoring case considerations.
inthashCode()Returns a hash code for this string.
intindexOf(int ch)Returns the index within this string of the first occurrence of the specified character.
intindexOf(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.
intindexOf(String str)Returns the index within this string of the first occurrence of the specified substring.
intindexOf(String str, int fromIndex)Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
intlastIndexOf(int ch)Returns the index within this string of the last occurrence of the specified character.
intlastIndexOf(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.
intlastIndexOf(String str)Returns the index within this string of the last occurrence of the specified substring.
intlastIndexOf(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.
Stringsubstring(int beginIndex)Returns a string that is a substring of this string.
Stringsubstring(int beginIndex, int endIndex)Returns a string that is a substring of this string.
Stringrepeat(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 TypeMethodDescription
booleanmatches(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.
Stringreplace(char oldChar, char newChar)Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
Stringreplace(CharSequence target, CharSequence replacement)Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
StringreplaceAll(String regex, String replacement)Replaces each substring of this string that matches the given regular expression with the given replacement.
StringreplaceFirst(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); // 比较地址  true
    
    String 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

ConstructorDescription
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 TypeMethodDescription
StringBufferappend(String str)Appends the specified string to this character sequence.
StringBufferappend(StringBuffer sb)Appends the specified StringBuffer to this sequence.
intcapacity()Returns the current capacity.
charcharAt(int index)Returns the char value in this sequence at the specified index.
StringBufferdelete(int start, int end)Removes the characters in a substring of this sequence.
StringBufferdeleteCharAt(int index)Removes the char at the specified position in this sequence.
StringBufferinsert(int offset, String str)Inserts the string into this character sequence.
intlastIndexOf(String str)Returns the index within this string of the last occurrence of the specified substring.
intlastIndexOf(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.
intlength()Returns the length (character count).
StringBufferreplace(int start, int end, String str)Replaces the characters in a substring of this sequence with characters in the specified String.
StringBufferreverse()Causes this character sequence to be replaced by the reverse of the sequence.
voidsetCharAt(int index, char ch)The character at the specified index is set to ch.
voidsetLength(int newLength)Sets the length of the character sequence.
Stringsubstring(int start)Returns a new String that contains a subsequence of characters currently contained in this character sequence.
Stringsubstring(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

ConstructorDescription
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 TypeMethodDescription
StringBufferappend(String str)Appends the specified string to this character sequence.
StringBufferappend(StringBuffer sb)Appends the specified StringBuffer to this sequence.
intcapacity()Returns the current capacity.
charcharAt(int index)Returns the char value in this sequence at the specified index.
StringBufferdelete(int start, int end)Removes the characters in a substring of this sequence.
StringBufferdeleteCharAt(int index)Removes the char at the specified position in this sequence.
StringBufferinsert(int offset, String str)Inserts the string into this character sequence.
intlastIndexOf(String str)Returns the index within this string of the last occurrence of the specified substring.
intlastIndexOf(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.
intlength()Returns the length (character count).
StringBufferreplace(int start, int end, String str)Replaces the characters in a substring of this sequence with characters in the specified String.
StringBufferreverse()Causes this character sequence to be replaced by the reverse of the sequence.
voidsetCharAt(int index, char ch)The character at the specified index is set to ch.
voidsetLength(int newLength)Sets the length of the character sequence.
Stringsubstring(int start)Returns a new String that contains a subsequence of characters currently contained in this character sequence.
Stringsubstring(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 TypeMethodDescription
static longcurrentTimeMillis()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

ConstructorDescription
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 TypeMethodDescription
booleanafter(Date when)Tests if this date is after the specified date.
booleanbefore(Date when)Tests if this date is before the specified date.
intcompareTo(Date anotherDate)Compares two Dates for ordering.
booleanequals(Object obj)Compares two dates for equality.
static Datefrom(Instant instant)Obtains an instance of Date from an Instant object.
intgetDate()**Deprecated.**As of JDK version 1.1, replaced by Calendar.get(Calendar.DAY_OF_MONTH).
intgetDay()**Deprecated.**As of JDK version 1.1, replaced by Calendar.get(Calendar.DAY_OF_WEEK).
intgetHours()**Deprecated.**As of JDK version 1.1, replaced by Calendar.get(Calendar.HOUR_OF_DAY).
intgetMinutes()**Deprecated.**As of JDK version 1.1, replaced by Calendar.get(Calendar.MINUTE).
intgetMonth()**Deprecated.**As of JDK version 1.1, replaced by Calendar.get(Calendar.MONTH).
intgetSeconds()**Deprecated.**As of JDK version 1.1, replaced by Calendar.get(Calendar.SECOND).
longgetTime()Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
intgetTimezoneOffset()**Deprecated.**As of JDK version 1.1, replaced by -(Calendar.get(Calendar.ZONE_OFFSET) + Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000).
intgetYear()**Deprecated.**As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.
inthashCode()Returns a hash code value for this object.
static longparse(String s)**Deprecated.**As of JDK version 1.1, replaced by DateFormat.parse(String s).
voidsetDate(int date)**Deprecated.**As of JDK version 1.1, replaced by Calendar.set(Calendar.DAY_OF_MONTH, int date).
voidsetHours(int hours)**Deprecated.**As of JDK version 1.1, replaced by Calendar.set(Calendar.HOUR_OF_DAY, int hours).
voidsetMinutes(int minutes)**Deprecated.**As of JDK version 1.1, replaced by Calendar.set(Calendar.MINUTE, int minutes).
voidsetMonth(int month)**Deprecated.**As of JDK version 1.1, replaced by Calendar.set(Calendar.MONTH, int month).
voidsetSeconds(int seconds)**Deprecated.**As of JDK version 1.1, replaced by Calendar.set(Calendar.SECOND, int seconds).
voidsetTime(long time)Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.
voidsetYear(int year)**Deprecated.**As of JDK version 1.1, replaced by Calendar.set(Calendar.YEAR, year + 1900).
StringtoGMTString()**Deprecated.**As of JDK version 1.1, replaced by DateFormat.format(Date date), using a GMT TimeZone.
InstanttoInstant()Converts this Date object to an Instant.
StringtoLocaleString()**Deprecated.**As of JDK version 1.1, replaced by DateFormat.format(Date date).
StringtoString()Converts this Date object to a String of the form:
static longUTC(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

ConstructorDescription
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 TypeMethodDescription
Stringformat(Date date)Formats a Date into a date-time string.
Dateparse(String source)Parses text from the beginning of the given string to produce a date.
@Test
    public 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

LetterDate or Time ComponentPresentationExamples
GEra designatorTextAD
yYearYear1996; 96
YWeek yearYear2009; 09
MMonth in year (context sensitive)MonthJuly; Jul; 07
LMonth in year (standalone form)MonthJuly; Jul; 07
wWeek in yearNumber27
WWeek in monthNumber2
DDay in yearNumber189
dDay in monthNumber10
FDay of week in monthNumber2
EDay name in weekTextTuesday; Tue
uDay number of week (1 = Monday, …, 7 = Sunday)Number1
aAm/pm markerTextPM
HHour in day (0-23)Number0
kHour in day (1-24)Number24
KHour in am/pm (0-11)Number0
hHour in am/pm (1-12)Number12
mMinute in hourNumber30
sSecond in minuteNumber55
SMillisecondNumber978
zTime zoneGeneral time zonePacific Standard Time; PST; GMT-08:00
ZTime zoneRFC 822 time zone-0800
XTime zoneISO 8601 time zone-08; -0800; -08:00

Examples:

Date and Time PatternResult
"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 TypeFieldDescription
static intALL_STYLESA style specifier for getDisplayNames indicating names in all styles, such as “January” and “Jan”.
static intAMValue of the AM_PM field indicating the period of the day from midnight to just before noon.
static intAM_PMField number for get and set indicating whether the HOUR is before or after noon.
static intAPRILValue of the MONTH field indicating the fourth month of the year in the Gregorian and Julian calendars.
protected booleanareFieldsSetTrue if fields[] are in sync with the currently set time.
static intAUGUSTValue of the MONTH field indicating the eighth month of the year in the Gregorian and Julian calendars.
static intDATEField number for get and set indicating the day of the month.
static intDAY_OF_MONTHField number for get and set indicating the day of the month.
static intDAY_OF_WEEKField number for get and set indicating the day of the week.
static intDAY_OF_WEEK_IN_MONTHField number for get and set indicating the ordinal number of the day of the week within the current month.
static intDAY_OF_YEARField number for get and set indicating the day number within the current year.
static intDECEMBERValue of the MONTH field indicating the twelfth month of the year in the Gregorian and Julian calendars.
static intDST_OFFSETField number for get and set indicating the daylight saving offset in milliseconds.
static intERAField number for get and set indicating the era, e.g., AD or BC in the Julian calendar.
static intFEBRUARYValue of the MONTH field indicating the second month of the year in the Gregorian and Julian calendars.
static intFIELD_COUNTThe number of distinct fields recognized by get and set.
protected int[]fieldsThe calendar field values for the currently set time for this calendar.
static intFRIDAYValue of the DAY_OF_WEEK field indicating Friday.
static intHOURField number for get and set indicating the hour of the morning or afternoon.
static intHOUR_OF_DAYField number for get and set indicating the hour of the day.
protected boolean[]isSetThe flags which tell if a specified calendar field for the calendar is set.
protected booleanisTimeSetTrue if then the value of time is valid.
static intJANUARYValue of the MONTH field indicating the first month of the year in the Gregorian and Julian calendars.
static intJULYValue of the MONTH field indicating the seventh month of the year in the Gregorian and Julian calendars.
static intJUNEValue of the MONTH field indicating the sixth month of the year in the Gregorian and Julian calendars.
static intLONGA style specifier for getDisplayName and getDisplayNames equivalent to LONG_FORMAT.
static intLONG_FORMATA style specifier for getDisplayName and getDisplayNames indicating a long name used for format.
static intLONG_STANDALONEA style specifier for getDisplayName and getDisplayNames indicating a long name used independently, such as a month name as calendar headers.
static intMARCHValue of the MONTH field indicating the third month of the year in the Gregorian and Julian calendars.
static intMAYValue of the MONTH field indicating the fifth month of the year in the Gregorian and Julian calendars.
static intMILLISECONDField number for get and set indicating the millisecond within the second.
static intMINUTEField number for get and set indicating the minute within the hour.
static intMONDAYValue of the DAY_OF_WEEK field indicating Monday.
static intMONTHField number for get and set indicating the month.
static intNARROW_FORMATA style specifier for getDisplayName and getDisplayNames indicating a narrow name used for format.
static intNARROW_STANDALONEA style specifier for getDisplayName and getDisplayNames indicating a narrow name independently.
static intNOVEMBERValue of the MONTH field indicating the eleventh month of the year in the Gregorian and Julian calendars.
static intOCTOBERValue of the MONTH field indicating the tenth month of the year in the Gregorian and Julian calendars.
static intPMValue of the AM_PM field indicating the period of the day from noon to just before midnight.
static intSATURDAYValue of the DAY_OF_WEEK field indicating Saturday.
static intSECONDField number for get and set indicating the second within the minute.
static intSEPTEMBERValue of the MONTH field indicating the ninth month of the year in the Gregorian and Julian calendars.
static intSHORTA style specifier for getDisplayName and getDisplayNames equivalent to SHORT_FORMAT.
static intSHORT_FORMATA style specifier for getDisplayName and getDisplayNames indicating a short name used for format.
static intSHORT_STANDALONEA style specifier for getDisplayName and getDisplayNames indicating a short name used independently, such as a month abbreviation as calendar headers.
static intSUNDAYValue of the DAY_OF_WEEK field indicating Sunday.
static intTHURSDAYValue of the DAY_OF_WEEK field indicating Thursday.
protected longtimeThe currently set time for this calendar, expressed in milliseconds after January 1, 1970, 0:00:00 GMT.
static intTUESDAYValue of the DAY_OF_WEEK field indicating Tuesday.
static intUNDECIMBERValue of the MONTH field indicating the thirteenth month of the year.
static intWEDNESDAYValue of the DAY_OF_WEEK field indicating Wednesday.
static intWEEK_OF_MONTHField number for get and set indicating the week number within the current month.
static intWEEK_OF_YEARField number for get and set indicating the week number within the current year.
static intYEARField number for get and set indicating the year.
static intZONE_OFFSETField number for get and set indicating the raw offset from GMT in milliseconds.

Constructors

ModifierConstructorDescription
protectedCalendar()Constructs a Calendar with the default time zone and the default FORMAT locale.
protectedCalendar(TimeZone zone, Locale aLocale)Constructs a calendar with the specified time zone and locale.

Methods

Modifier and TypeMethodDescription
abstract voidadd(int field, int amount)Adds or subtracts the specified amount of time to the given calendar field, based on the calendar’s rules.
booleanafter(Object when)Returns whether this Calendar represents a time after the time represented by the specified Object.
booleanbefore(Object when)Returns whether this Calendar represents a time before the time represented by the specified Object.
voidclear()Sets all the calendar field values and the time value (millisecond offset from the Epoch) of this Calendar undefined.
voidclear(int field)Sets the given calendar field value and the time value (millisecond offset from the Epoch) of this Calendar undefined.
Objectclone()Creates and returns a copy of this object.
intcompareTo(Calendar anotherCalendar)Compares the time values (millisecond offsets from the Epoch) represented by two Calendar objects.
protected voidcomplete()Fills in any unset fields in the calendar fields.
protected abstract voidcomputeFields()Converts the current millisecond time value time to calendar field values in fields[\].
protected abstract voidcomputeTime()Converts the current calendar field values in fields[\] to the millisecond time value time.
booleanequals(Object obj)Compares this Calendar to the specified Object.
intget(int field)Returns the value of the given calendar field.
intgetActualMaximum(int field)Returns the maximum value that the specified calendar field could have, given the time value of this Calendar.
intgetActualMinimum(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.
StringgetCalendarType()Returns the calendar type of this Calendar.
StringgetDisplayName(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.
intgetFirstDayOfWeek()Gets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France.
abstract intgetGreatestMinimum(int field)Returns the highest minimum value for the given calendar field of this Calendar instance.
static CalendargetInstance()Gets a calendar using the default time zone and locale.
static CalendargetInstance(Locale aLocale)Gets a calendar using the default time zone and specified locale.
static CalendargetInstance(TimeZone zone)Gets a calendar using the specified time zone and default locale.
static CalendargetInstance(TimeZone zone, Locale aLocale)Gets a calendar with the specified time zone and locale.
abstract intgetLeastMaximum(int field)Returns the lowest maximum value for the given calendar field of this Calendar instance.
abstract intgetMaximum(int field)Returns the maximum value for the given calendar field of this Calendar instance.
intgetMinimalDaysInFirstWeek()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 intgetMinimum(int field)Returns the minimum value for the given calendar field of this Calendar instance.
DategetTime()Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").
longgetTimeInMillis()Returns this Calendar’s time value in milliseconds.
TimeZonegetTimeZone()Gets the time zone.
intgetWeeksInWeekYear()Returns the number of weeks in the week year represented by this Calendar.
intgetWeekYear()Returns the week year represented by this Calendar.
inthashCode()Returns a hash code for this calendar.
protected intinternalGet(int field)Returns the value of the given calendar field.
booleanisLenient()Tells whether date/time interpretation is to be lenient.
booleanisSet(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.
booleanisWeekDateSupported()Returns whether this Calendar supports week dates.
abstract voidroll(int field, boolean up)Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
voidroll(int field, int amount)Adds the specified (signed) amount to the specified calendar field without changing larger fields.
voidset(int field, int value)Sets the given calendar field to the given value.
voidset(int year, int month, int date)Sets the values for the calendar fields YEAR, MONTH(starts from 0), and DAY_OF_MONTH.
voidset(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.
voidset(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.
voidsetFirstDayOfWeek(int value)Sets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France.
voidsetLenient(boolean lenient)Specifies whether or not date/time interpretation is to be lenient.
voidsetMinimalDaysInFirstWeek(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.
voidsetTime(Date date)Sets this Calendar’s time with the given Date.
voidsetTimeInMillis(long millis)Sets this Calendar’s current time from the given long value.
voidsetTimeZone(TimeZone value)Sets the time zone with the given time zone value.
voidsetWeekDate(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.
InstanttoInstant()Converts this object to an Instant.
StringtoString()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

ConstructorDescription
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 TypeMethodDescription
voidadd(int field, int amount)Adds the specified (signed) amount of time to the given calendar field, based on the calendar’s rules.
protected voidcomputeFields()Converts the time value (millisecond offset from the Epoch) to calendar field values.
protected voidcomputeTime()Converts calendar field values to the time value (millisecond offset from the Epoch).
booleanequals(Object obj)Compares this GregorianCalendar to the specified Object.
static GregorianCalendarfrom(ZonedDateTime zdt)Obtains an instance of GregorianCalendar with the default locale from a ZonedDateTime object.
intgetActualMaximum(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.
intgetActualMinimum(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.
StringgetCalendarType()Returns "gregory" as the calendar type.
intgetGreatestMinimum(int field)Returns the highest minimum value for the given calendar field of this GregorianCalendar instance.
DategetGregorianChange()Gets the Gregorian Calendar change date.
intgetLeastMaximum(int field)Returns the lowest maximum value for the given calendar field of this GregorianCalendar instance.
intgetMaximum(int field)Returns the maximum value for the given calendar field of this GregorianCalendar instance.
intgetMinimum(int field)Returns the minimum value for the given calendar field of this GregorianCalendar instance.
intgetWeeksInWeekYear()Returns the number of weeks in the week year represented by this GregorianCalendar.
intgetWeekYear()Returns the week year represented by this GregorianCalendar.
inthashCode()Generates the hash code for this GregorianCalendar object.
booleanisLeapYear(int year)Determines if the given year is a leap year.
booleanisWeekDateSupported()Returns true indicating this GregorianCalendar supports week dates.
voidroll(int field, boolean up)Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
voidroll(int field, int amount)Adds a signed amount to the specified calendar field without changing larger fields.
voidsetGregorianChange(Date date)Sets the GregorianCalendar change date.
voidsetWeekDate(int weekYear, int weekOfYear, int dayOfWeek)Sets this GregorianCalendar to the date given by the date specifiers - weekYear, weekOfYear, and dayOfWeek.
ZonedDateTimetoZonedDateTime()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 TypeFieldDescription
static LocalDateEPOCHThe epoch year LocalDate, ‘1970-01-01’.
static LocalDateMAXThe maximum supported LocalDate, ‘+999999999-12-31’.
static LocalDateMINThe minimum supported LocalDate, ‘-999999999-01-01’.
Methods
Modifier and TypeMethodDescription
static LocalDatenow()Obtains the current date from the system clock in the default time-zone.
static LocalDatenow(Clock clock)Obtains the current date from the specified clock.
static LocalDatenow(ZoneId zone)Obtains the current date from the system clock in the specified time-zone.
TemporaladjustInto(Temporal temporal)Adjusts the specified temporal object to have the same date as this object.
LocalDateTimeatStartOfDay()Combines this date with the time of midnight to create a LocalDateTime at the start of this date.
ZonedDateTimeatStartOfDay(ZoneId zone)Returns a zoned date-time from this date at the earliest valid time according to the rules in the time-zone.
LocalDateTimeatTime(int hour, int minute)Combines this date with a time to create a LocalDateTime.
LocalDateTimeatTime(int hour, int minute, int second)Combines this date with a time to create a LocalDateTime.
LocalDateTimeatTime(int hour, int minute, int second, int nanoOfSecond)Combines this date with a time to create a LocalDateTime.
LocalDateTimeatTime(LocalTime time)Combines this date with a time to create a LocalDateTime.
OffsetDateTimeatTime(OffsetTime time)Combines this date with an offset time to create an OffsetDateTime.
intcompareTo(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.
booleanequals(Object obj)Checks if this date is equal to another date.
Stringformat(DateTimeFormatter formatter)Formats this date using the specified formatter.
static LocalDatefrom(TemporalAccessor temporal)Obtains an instance of LocalDate from a temporal object.
intget(TemporalField field)Gets the value of the specified field from this date as an int.
IsoChronologygetChronology()Gets the chronology of this date, which is the ISO calendar system.
intgetDayOfMonth()Gets the day-of-month field.
DayOfWeekgetDayOfWeek()Gets the day-of-week field, which is an enum DayOfWeek.
intgetDayOfYear()Gets the day-of-year field.
IsoEragetEra()Gets the era applicable at this date.
longgetLong(TemporalField field)Gets the value of the specified field from this date as a long.
MonthgetMonth()Gets the month-of-year field using the Month enum.
intgetMonthValue()Gets the month-of-year field from 1 to 12.
intgetYear()Gets the year field.
inthashCode()A hash code for this date.
booleanisAfter(ChronoLocalDate other)Checks if this date is after the specified date.
booleanisBefore(ChronoLocalDate other)Checks if this date is before the specified date.
booleanisEqual(ChronoLocalDate other)Checks if this date is equal to the specified date.
booleanisLeapYear()Checks if the year is a leap year, according to the ISO proleptic calendar system rules.
booleanisSupported(TemporalField field)Checks if the specified field is supported.
booleanisSupported(TemporalUnit unit)Checks if the specified unit is supported.
intlengthOfMonth()Returns the length of the month represented by this date.
intlengthOfYear()Returns the length of the year represented by this date.
LocalDateminus(long amountToSubtract, TemporalUnit unit)Returns a copy of this date with the specified amount subtracted.
LocalDateminus(TemporalAmount amountToSubtract)Returns a copy of this date with the specified amount subtracted.
LocalDateminusDays(long daysToSubtract)Returns a copy of this LocalDate with the specified number of days subtracted.
LocalDateminusMonths(long monthsToSubtract)Returns a copy of this LocalDate with the specified number of months subtracted.
LocalDateminusWeeks(long weeksToSubtract)Returns a copy of this LocalDate with the specified number of weeks subtracted.
LocalDateminusYears(long yearsToSubtract)Returns a copy of this LocalDate with the specified number of years subtracted.
static LocalDateof(int year, int month, int dayOfMonth)Obtains an instance of LocalDate from a year, month and day.
static LocalDateof(int year, Month month, int dayOfMonth)Obtains an instance of LocalDate from a year, month and day.
static LocalDateofEpochDay(long epochDay)Obtains an instance of LocalDate from the epoch day count.
static LocalDateofInstant(Instant instant, ZoneId zone)Obtains an instance of LocalDate from an Instant and zone ID.
static LocalDateofYearDay(int year, int dayOfYear)Obtains an instance of LocalDate from a year and day-of-year.
static LocalDateparse(CharSequence text)Obtains an instance of LocalDate from a text string such as 2007-12-03.
static LocalDateparse(CharSequence text, DateTimeFormatter formatter)Obtains an instance of LocalDate from a text string using a specific formatter.
LocalDateplus(long amountToAdd, TemporalUnit unit)Returns a copy of this date with the specified amount added.
LocalDateplus(TemporalAmount amountToAdd)Returns a copy of this date with the specified amount added.
LocalDateplusDays(long daysToAdd)Returns a copy of this LocalDate with the specified number of days added.
LocalDateplusMonths(long monthsToAdd)Returns a copy of this LocalDate with the specified number of months added.
LocalDateplusWeeks(long weeksToAdd)Returns a copy of this LocalDate with the specified number of weeks added.
LocalDateplusYears(long yearsToAdd)Returns a copy of this LocalDate with the specified number of years added.
<R> Rquery(TemporalQuery<R> query)Queries this date using the specified query.
ValueRangerange(TemporalField field)Gets the range of valid values for the specified field.
longtoEpochSecond(LocalTime time, ZoneOffset offset)Converts this LocalDate to the number of seconds since the epoch of 1970-01-01T00:00:00Z.
StringtoString()Outputs this date as a String, such as 2007-12-03.
Perioduntil(ChronoLocalDate endDateExclusive)Calculates the period between this date and another date as a Period.
longuntil(Temporal endExclusive, TemporalUnit unit)Calculates the amount of time until another date in terms of the specified unit.
LocalDatewith(TemporalAdjuster adjuster)Returns an adjusted copy of this date.
LocalDatewith(TemporalField field, long newValue)Returns a copy of this date with the specified field set to a new value.
LocalDatewithDayOfMonth(int dayOfMonth)Returns a copy of this LocalDate with the day-of-month altered.
LocalDatewithDayOfYear(int dayOfYear)Returns a copy of this LocalDate with the day-of-year altered.
LocalDatewithMonth(int month)Returns a copy of this LocalDate with the month-of-year altered.
LocalDatewithYear(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 TypeFieldDescription
static LocalDateTimeMAXThe maximum supported LocalDateTime, ‘+999999999-12-31T23:59:59.999999999’.
static LocalDateTimeMINThe minimum supported LocalDateTime, ‘-999999999-01-01T00:00:00’.
Methods
Modifier and TypeMethodDescription
TemporaladjustInto(Temporal temporal)Adjusts the specified temporal object to have the same date and time as this object.
OffsetDateTimeatOffset(ZoneOffset offset)Combines this date-time with an offset to create an OffsetDateTime.
ZonedDateTimeatZone(ZoneId zone)Combines this date-time with a time-zone to create a ZonedDateTime.
intcompareTo(ChronoLocalDateTime<?> other)Compares this date-time to another date-time.
booleanequals(Object obj)Checks if this date-time is equal to another date-time.
Stringformat(DateTimeFormatter formatter)Formats this date-time using the specified formatter.
static LocalDateTimefrom(TemporalAccessor temporal)Obtains an instance of LocalDateTime from a temporal object.
intget(TemporalField field)Gets the value of the specified field from this date-time as an int.
intgetDayOfMonth()Gets the day-of-month field.
DayOfWeekgetDayOfWeek()Gets the day-of-week field, which is an enum DayOfWeek.
intgetDayOfYear()Gets the day-of-year field.
intgetHour()Gets the hour-of-day field.
longgetLong(TemporalField field)Gets the value of the specified field from this date-time as a long.
intgetMinute()Gets the minute-of-hour field.
MonthgetMonth()Gets the month-of-year field using the Month enum.
intgetMonthValue()Gets the month-of-year field from 1 to 12.
intgetNano()Gets the nano-of-second field.
intgetSecond()Gets the second-of-minute field.
intgetYear()Gets the year field.
inthashCode()A hash code for this date-time.
booleanisAfter(ChronoLocalDateTime<?> other)Checks if this date-time is after the specified date-time.
booleanisBefore(ChronoLocalDateTime<?> other)Checks if this date-time is before the specified date-time.
booleanisEqual(ChronoLocalDateTime<?> other)Checks if this date-time is equal to the specified date-time.
booleanisSupported(TemporalField field)Checks if the specified field is supported.
booleanisSupported(TemporalUnit unit)Checks if the specified unit is supported.
LocalDateTimeminus(long amountToSubtract, TemporalUnit unit)Returns a copy of this date-time with the specified amount subtracted.
LocalDateTimeminus(TemporalAmount amountToSubtract)Returns a copy of this date-time with the specified amount subtracted.
LocalDateTimeminusDays(long days)Returns a copy of this LocalDateTime with the specified number of days subtracted.
LocalDateTimeminusHours(long hours)Returns a copy of this LocalDateTime with the specified number of hours subtracted.
LocalDateTimeminusMinutes(long minutes)Returns a copy of this LocalDateTime with the specified number of minutes subtracted.
LocalDateTimeminusMonths(long months)Returns a copy of this LocalDateTime with the specified number of months subtracted.
LocalDateTimeminusNanos(long nanos)Returns a copy of this LocalDateTime with the specified number of nanoseconds subtracted.
LocalDateTimeminusSeconds(long seconds)Returns a copy of this LocalDateTime with the specified number of seconds subtracted.
LocalDateTimeminusWeeks(long weeks)Returns a copy of this LocalDateTime with the specified number of weeks subtracted.
LocalDateTimeminusYears(long years)Returns a copy of this LocalDateTime with the specified number of years subtracted.
static LocalDateTimenow()Obtains the current date-time from the system clock in the default time-zone.
static LocalDateTimenow(Clock clock)Obtains the current date-time from the specified clock.
static LocalDateTimenow(ZoneId zone)Obtains the current date-time from the system clock in the specified time-zone.
static LocalDateTimeof(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 LocalDateTimeof(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 LocalDateTimeof(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 LocalDateTimeof(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 LocalDateTimeof(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 LocalDateTimeof(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 LocalDateTimeof(LocalDate date, LocalTime time)Obtains an instance of LocalDateTime from a date and time.
static LocalDateTimeofEpochSecond(long epochSecond, int nanoOfSecond, ZoneOffset offset)Obtains an instance of LocalDateTime using seconds from the epoch of 1970-01-01T00:00:00Z.
static LocalDateTimeofInstant(Instant instant, ZoneId zone)Obtains an instance of LocalDateTime from an Instant and zone ID.
static LocalDateTimeparse(CharSequence text)Obtains an instance of LocalDateTime from a text string such as 2007-12-03T10:15:30.
static LocalDateTimeparse(CharSequence text, DateTimeFormatter formatter)Obtains an instance of LocalDateTime from a text string using a specific formatter.
LocalDateTimeplus(long amountToAdd, TemporalUnit unit)Returns a copy of this date-time with the specified amount added.
LocalDateTimeplus(TemporalAmount amountToAdd)Returns a copy of this date-time with the specified amount added.
LocalDateTimeplusDays(long days)Returns a copy of this LocalDateTime with the specified number of days added.
LocalDateTimeplusHours(long hours)Returns a copy of this LocalDateTime with the specified number of hours added.
LocalDateTimeplusMinutes(long minutes)Returns a copy of this LocalDateTime with the specified number of minutes added.
LocalDateTimeplusMonths(long months)Returns a copy of this LocalDateTime with the specified number of months added.
LocalDateTimeplusNanos(long nanos)Returns a copy of this LocalDateTime with the specified number of nanoseconds added.
LocalDateTimeplusSeconds(long seconds)Returns a copy of this LocalDateTime with the specified number of seconds added.
LocalDateTimeplusWeeks(long weeks)Returns a copy of this LocalDateTime with the specified number of weeks added.
LocalDateTimeplusYears(long years)Returns a copy of this LocalDateTime with the specified number of years added.
<R> Rquery(TemporalQuery<R> query)Queries this date-time using the specified query.
ValueRangerange(TemporalField field)Gets the range of valid values for the specified field.
LocalDatetoLocalDate()Gets the LocalDate part of this date-time.
LocalTimetoLocalTime()Gets the LocalTime part of this date-time.
StringtoString()Outputs this date-time as a String, such as 2007-12-03T10:15:30.
LocalDateTimetruncatedTo(TemporalUnit unit)Returns a copy of this LocalDateTime with the time truncated.
longuntil(Temporal endExclusive, TemporalUnit unit)Calculates the amount of time until another date-time in terms of the specified unit.
LocalDateTimewith(TemporalAdjuster adjuster)Returns an adjusted copy of this date-time.
LocalDateTimewith(TemporalField field, long newValue)Returns a copy of this date-time with the specified field set to a new value.
LocalDateTimewithDayOfMonth(int dayOfMonth)Returns a copy of this LocalDateTime with the day-of-month altered.
LocalDateTimewithDayOfYear(int dayOfYear)Returns a copy of this LocalDateTime with the day-of-year altered.
LocalDateTimewithHour(int hour)Returns a copy of this LocalDateTime with the hour-of-day altered.
LocalDateTimewithMinute(int minute)Returns a copy of this LocalDateTime with the minute-of-hour altered.
LocalDateTimewithMonth(int month)Returns a copy of this LocalDateTime with the month-of-year altered.
LocalDateTimewithNano(int nanoOfSecond)Returns a copy of this LocalDateTime with the nano-of-second altered.
LocalDateTimewithSecond(int second)Returns a copy of this LocalDateTime with the second-of-minute altered.
LocalDateTimewithYear(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 TypeFieldDescription
static InstantEPOCHConstant for the 1970-01-01T00:00:00Z epoch instant.
static InstantMAXThe maximum supported Instant, ‘1000000000-12-31T23:59:59.999999999Z’.
static InstantMINThe minimum supported Instant, ‘-1000000000-01-01T00:00Z’.
Methods
Modifier and TypeMethodDescription
TemporaladjustInto(Temporal temporal)Adjusts the specified temporal object to have this instant.
OffsetDateTimeatOffset(ZoneOffset offset)Combines this instant with an offset to create an OffsetDateTime.
ZonedDateTimeatZone(ZoneId zone)Combines this instant with a time-zone to create a ZonedDateTime.
intcompareTo(Instant otherInstant)Compares this instant to the specified instant.
booleanequals(Object otherInstant)Checks if this instant is equal to the specified instant.
static Instantfrom(TemporalAccessor temporal)Obtains an instance of Instant from a temporal object.
intget(TemporalField field)Gets the value of the specified field from this instant as an int.
longgetEpochSecond()Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z.
longgetLong(TemporalField field)Gets the value of the specified field from this instant as a long.
intgetNano()Gets the number of nanoseconds, later along the time-line, from the start of the second.
inthashCode()Returns a hash code for this instant.
booleanisAfter(Instant otherInstant)Checks if this instant is after the specified instant.
booleanisBefore(Instant otherInstant)Checks if this instant is before the specified instant.
booleanisSupported(TemporalField field)Checks if the specified field is supported.
booleanisSupported(TemporalUnit unit)Checks if the specified unit is supported.
Instantminus(long amountToSubtract, TemporalUnit unit)Returns a copy of this instant with the specified amount subtracted.
Instantminus(TemporalAmount amountToSubtract)Returns a copy of this instant with the specified amount subtracted.
InstantminusMillis(long millisToSubtract)Returns a copy of this instant with the specified duration in milliseconds subtracted.
InstantminusNanos(long nanosToSubtract)Returns a copy of this instant with the specified duration in nanoseconds subtracted.
InstantminusSeconds(long secondsToSubtract)Returns a copy of this instant with the specified duration in seconds subtracted.
static Instantnow()Obtains the current instant from the system clock (UTC 0).
static Instantnow(Clock clock)Obtains the current instant from the specified clock.
static InstantofEpochMilli(long epochMilli)Obtains an instance of Instant using milliseconds from the epoch of 1970-01-01T00:00:00Z.
static InstantofEpochSecond(long epochSecond)Obtains an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z.
static InstantofEpochSecond(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 Instantparse(CharSequence text)Obtains an instance of Instant from a text string such as 2007-12-03T10:15:30.00Z.
Instantplus(long amountToAdd, TemporalUnit unit)Returns a copy of this instant with the specified amount added.
Instantplus(TemporalAmount amountToAdd)Returns a copy of this instant with the specified amount added.
InstantplusMillis(long millisToAdd)Returns a copy of this instant with the specified duration in milliseconds added.
InstantplusNanos(long nanosToAdd)Returns a copy of this instant with the specified duration in nanoseconds added.
InstantplusSeconds(long secondsToAdd)Returns a copy of this instant with the specified duration in seconds added.
<R> Rquery(TemporalQuery<R> query)Queries this instant using the specified query.
ValueRangerange(TemporalField field)Gets the range of valid values for the specified field.
longtoEpochMilli()Converts this instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z.
StringtoString()A string representation of this instant using ISO-8601 representation.
InstanttruncatedTo(TemporalUnit unit)Returns a copy of this Instant truncated to the specified unit.
longuntil(Temporal endExclusive, TemporalUnit unit)Calculates the amount of time until another instant in terms of the specified unit.
Instantwith(TemporalAdjuster adjuster)Returns an adjusted copy of this instant.
Instantwith(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

FormatterDescriptionExample
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_DATEBasic ISO date‘20111203’
ISO_LOCAL_DATEISO Local Date‘2011-12-03’
ISO_OFFSET_DATEISO Date with offset‘2011-12-03+01:00’
ISO_DATEISO Date with or without offset‘2011-12-03+01:00’; ‘2011-12-03’
ISO_LOCAL_TIMETime without offset‘10:15:30’
ISO_OFFSET_TIMETime with offset‘10:15:30+01:00’
ISO_TIMETime with or without offset‘10:15:30+01:00’; ‘10:15:30’
ISO_LOCAL_DATE_TIMEISO Local Date and Time‘2011-12-03T10:15:30’
ISO_OFFSET_DATE_TIMEDate Time with Offset‘2011-12-03T10:15:30+01:00’
ISO_ZONED_DATE_TIMEZoned Date Time‘2011-12-03T10:15:30+01:00[Europe/Paris]’
ISO_DATE_TIMEDate and time with ZoneId‘2011-12-03T10:15:30+01:00[Europe/Paris]’
ISO_ORDINAL_DATEYear and day of year‘2012-337’
ISO_WEEK_DATEYear and Week‘2012-W48-6’
ISO_INSTANTDate and Time of an Instant‘2011-12-03T10:15:30Z’
RFC_1123_DATE_TIMERFC 1123 / RFC 822‘Tue, 3 Jun 2008 11:05:30 GMT’

Pattern Letters and Symbols

SymbolMeaningPresentationExamples
GeratextAD; Anno Domini; A
uyearyear2004; 04
yyear-of-erayear2004; 04
Dday-of-yearnumber189
M/Lmonth-of-yearnumber/text7; 07; Jul; July; J
dday-of-monthnumber10
gmodified-julian-daynumber2451334
Q/qquarter-of-yearnumber/text3; 03; Q3; 3rd quarter
Yweek-based-yearyear1996; 96
wweek-of-week-based-yearnumber27
Wweek-of-monthnumber4
Eday-of-weektextTue; Tuesday; T
e/clocalized day-of-weeknumber/text2; 02; Tue; Tuesday; T
Fday-of-week-in-monthnumber3
aam-pm-of-daytextPM
hclock-hour-of-am-pm (1-12)number12
Khour-of-am-pm (0-11)number0
kclock-hour-of-day (1-24)number24
Hhour-of-day (0-23)number0
mminute-of-hournumber30
ssecond-of-minutenumber55
Sfraction-of-secondfraction978
Amilli-of-daynumber1234
nnano-of-secondnumber987654321
Nnano-of-daynumber1234000000
Vtime-zone IDzone-idAmerica/Los_Angeles; Z; -08:30
vgeneric time-zone namezone-namePacific Time; PT
ztime-zone namezone-namePacific Standard Time; PST
Olocalized zone-offsetoffset-OGMT+8; GMT+08:00; UTC-08:00
Xzone-offset ‘Z’ for zerooffset-XZ; -08; -0830; -08:30; -083015; -08:30:15
xzone-offsetoffset-x+0000; -08; -0830; -08:30; -083015; -08:30:15
Zzone-offsetoffset-Z+0000; -0800; -08:00
ppad nextpad modifier1
escape for textdelimiter
‘’single quoteliteral
[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 TypeFieldDescription
static DateTimeFormatterBASIC_ISO_DATEThe ISO date formatter that formats or parses a date without an offset, such as ‘20111203’.
static DateTimeFormatterISO_DATEThe 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 DateTimeFormatterISO_DATE_TIMEThe 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 DateTimeFormatterISO_INSTANTThe ISO instant formatter that formats or parses an instant in UTC, such as ‘2011-12-03T10:15:30Z’.
static DateTimeFormatterISO_LOCAL_DATEThe ISO date formatter that formats or parses a date without an offset, such as ‘2011-12-03’.
static DateTimeFormatterISO_LOCAL_DATE_TIMEThe ISO date-time formatter that formats or parses a date-time without an offset, such as ‘2011-12-03T10:15:30’.
static DateTimeFormatterISO_LOCAL_TIMEThe ISO time formatter that formats or parses a time without an offset, such as ‘10:15’ or ‘10:15:30’.
static DateTimeFormatterISO_OFFSET_DATEThe ISO date formatter that formats or parses a date with an offset, such as ‘2011-12-03+01:00’.
static DateTimeFormatterISO_OFFSET_DATE_TIMEThe ISO date-time formatter that formats or parses a date-time with an offset, such as ‘2011-12-03T10:15:30+01:00’.
static DateTimeFormatterISO_OFFSET_TIMEThe 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 DateTimeFormatterISO_ORDINAL_DATEThe ISO date formatter that formats or parses the ordinal date without an offset, such as ‘2012-337’.
static DateTimeFormatterISO_TIMEThe 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 DateTimeFormatterISO_WEEK_DATEThe ISO date formatter that formats or parses the week-based date without an offset, such as ‘2012-W48-6’.
static DateTimeFormatterISO_ZONED_DATE_TIMEThe 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 DateTimeFormatterRFC_1123_DATE_TIMEThe RFC-1123 date-time formatter, such as ‘Tue, 3 Jun 2008 11:05:30 GMT’.

Methods

Modifier and TypeMethodDescription
Stringformat(TemporalAccessor temporal)Formats a date-time object using this formatter.
voidformatTo(TemporalAccessor temporal, Appendable appendable)Formats a date-time object to an Appendable using this formatter.
ChronologygetChronology()Gets the overriding chronology to be used during formatting.
DecimalStylegetDecimalStyle()Gets the DecimalStyle to be used during formatting.
LocalegetLocale()Gets the locale to be used during formatting.
Set<TemporalField>getResolverFields()Gets the resolver fields to use during parsing.
ResolverStylegetResolverStyle()Gets the resolver style to use during parsing.
ZoneIdgetZone()Gets the overriding zone to be used during formatting.
DateTimeFormatterlocalizedBy(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 DateTimeFormatterofLocalizedDate(FormatStyle dateStyle)Returns a locale specific date format for the ISO chronology.
static DateTimeFormatterofLocalizedDateTime(FormatStyle dateTimeStyle)Returns a locale specific date-time formatter for the ISO chronology.
static DateTimeFormatterofLocalizedDateTime(FormatStyle dateStyle, FormatStyle timeStyle)Returns a locale specific date and time format for the ISO chronology.
static DateTimeFormatterofLocalizedTime(FormatStyle timeStyle)Returns a locale specific time format for the ISO chronology.
static DateTimeFormatterofPattern(String pattern)Creates a formatter using the specified pattern.
static DateTimeFormatterofPattern(String pattern, Locale locale)Creates a formatter using the specified pattern and locale.
TemporalAccessorparse(CharSequence text)Fully parses the text producing a temporal object.
TemporalAccessorparse(CharSequence text, ParsePosition position)Parses the text using this formatter, providing control over the text position.
<T> Tparse(CharSequence text, TemporalQuery<T> query)Fully parses the text producing an object of the specified type.
TemporalAccessorparseBest(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.
TemporalAccessorparseUnresolved(CharSequence text, ParsePosition position)Parses the text using this formatter, without resolving the result, intended for advanced use cases.
FormattoFormat()Returns this formatter as a java.text.Format instance.
FormattoFormat(TemporalQuery<?> parseQuery)Returns this formatter as a java.text.Format instance that will parse using the specified query.
StringtoString()Returns a description of the underlying formatters.
DateTimeFormatterwithChronology(Chronology chrono)Returns a copy of this formatter with a new override chronology.
DateTimeFormatterwithDecimalStyle(DecimalStyle decimalStyle)Returns a copy of this formatter with a new DecimalStyle.
DateTimeFormatterwithLocale(Locale locale)Returns a copy of this formatter with a new locale.
DateTimeFormatterwithResolverFields(TemporalField... resolverFields)Returns a copy of this formatter with a new set of resolver fields.
DateTimeFormatterwithResolverFields(Set<TemporalField> resolverFields)Returns a copy of this formatter with a new set of resolver fields.
DateTimeFormatterwithResolverStyle(ResolverStyle resolverStyle)Returns a copy of this formatter with a new resolver style.
DateTimeFormatterwithZone(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 ConstantDescription
FULLFull text style, with the most detail.
LONGLong text style, with lots of detail.
MEDIUMMedium text style, with some detail.
SHORTShort 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 TypeClassDescription
static classLocale.BuilderBuilder is used to build instances of Locale from values configured by the setters.
static classLocale.CategoryEnum for locale categories.
static classLocale.FilteringModeThis enum provides constants to select a filtering mode for locale matching.
static classLocale.IsoCountryCodeEnum for specifying the type defined in ISO 3166.
static classLocale.LanguageRangeThis class expresses a Language Range defined in RFC 4647 Matching of Language Tags.

Fields

Modifier and TypeFieldDescription
static LocaleCANADAUseful constant for country.
static LocaleCANADA_FRENCHUseful constant for country.
static LocaleCHINAUseful constant for country.
static LocaleCHINESEUseful constant for language.
static LocaleENGLISHUseful constant for language.
static LocaleFRANCEUseful constant for country.
static LocaleFRENCHUseful constant for language.
static LocaleGERMANUseful constant for language.
static LocaleGERMANYUseful constant for country.
static LocaleITALIANUseful constant for language.
static LocaleITALYUseful constant for country.
static LocaleJAPANUseful constant for country.
static LocaleJAPANESEUseful constant for language.
static LocaleKOREAUseful constant for country.
static LocaleKOREANUseful constant for language.
static LocalePRCUseful constant for country.
static charPRIVATE_USE_EXTENSIONThe key for the private use extension (‘x’).
static LocaleROOTUseful constant for the root locale.
static LocaleSIMPLIFIED_CHINESEUseful constant for language.
static LocaleTAIWANUseful constant for country.
static LocaleTRADITIONAL_CHINESEUseful constant for language.
static LocaleUKUseful constant for country.
static charUNICODE_LOCALE_EXTENSIONThe key for Unicode locale extension (‘u’).
static LocaleUSUseful constant for country.

Constructors

ConstructorDescription
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 TypeMethodDescription
Objectclone()Overrides Cloneable.
booleanequals(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 LocaleforLanguageTag(String languageTag)Returns a locale for the specified IETF BCP 47 language tag string.
static Locale[]getAvailableLocales()Returns an array of all installed locales.
StringgetCountry()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 LocalegetDefault()Gets the current value of the default locale for this instance of the Java Virtual Machine.
static LocalegetDefault(Locale.Category category)Gets the current value of the default locale for the specified Category for this instance of the Java Virtual Machine.
StringgetDisplayCountry()Returns a name for the locale’s country that is appropriate for display to the user.
StringgetDisplayCountry(Locale inLocale)Returns a name for the locale’s country that is appropriate for display to the user.
StringgetDisplayLanguage()Returns a name for the locale’s language that is appropriate for display to the user.
StringgetDisplayLanguage(Locale inLocale)Returns a name for the locale’s language that is appropriate for display to the user.
StringgetDisplayName()Returns a name for the locale that is appropriate for display to the user.
StringgetDisplayName(Locale inLocale)Returns a name for the locale that is appropriate for display to the user.
StringgetDisplayScript()Returns a name for the locale’s script that is appropriate for display to the user.
StringgetDisplayScript(Locale inLocale)Returns a name for the locale’s script that is appropriate for display to the user.
StringgetDisplayVariant()Returns a name for the locale’s variant code that is appropriate for display to the user.
StringgetDisplayVariant(Locale inLocale)Returns a name for the locale’s variant code that is appropriate for display to the user.
StringgetExtension(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.
StringgetISO3Country()Returns a three-letter abbreviation for this locale’s country.
StringgetISO3Language()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.
StringgetLanguage()Returns the language code of this Locale.
StringgetScript()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.
StringgetUnicodeLocaleType(String key)Returns the Unicode locale type associated with the specified Unicode locale key for this locale.
StringgetVariant()Returns the variant code for this locale.
booleanhasExtensions()Returns true if this Locale has any extensions.
inthashCode()Override hashCode.
static Localelookup(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 StringlookupTag(List<Locale.LanguageRange> priorityList, Collection<String> tags)Returns the best-matching language tag using the lookup mechanism defined in RFC 4647.
static voidsetDefault(Locale newLocale)Sets the default locale for this instance of the Java Virtual Machine.
static voidsetDefault(Locale.Category category, Locale newLocale)Sets the default locale for the specified Category for this instance of the Java Virtual Machine.
LocalestripExtensions()Returns a copy of this Locale with no extensions.
StringtoLanguageTag()Returns a well-formed IETF BCP 47 language tag representing this locale.
StringtoString()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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值