Java Instant
Java Instant类用于表示时间轴上的特定时刻。它继承了Object类并实现Comparable接口。
Java Instant类声明
让我们看看java.time.Instant类的声明。
public final class Instant extends Object implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable
Java Instant方法
方法 |
说明 |
Temporal adjustInto(Temporal temporal) |
用于将指定的时间对象调整为具有此瞬间。 |
int get(TemporalField field) |
它用于从此刻以整数形式获取指定字段的值。 |
boolean isSupported(TemporalField field) |
用于检查是否支持指定的字段。 |
Instant minus(TemporalAmount amountToSubtract) |
用于返回此瞬间的副本,其中减去指定的数量。 |
static Instant now() |
用于从系统时钟获取当前时刻。 |
static Instant parse(CharSequence text) |
它用于从诸如2007-12-03T10: 15: 30.00Z之类的文本字符串中获取Instant实例。 |
Instant plus(TemporalAmount amountToAdd) |
它用于返回此瞬间的副本,并添加指定的数量。 |
Instant with(TemporalAdjuster adjuster) |
它用于返回此时刻的调整后副本。 |
Java即时示例: parse()
import java.time.Instant;
public class InstantExample1 {
public static void main(String[] args) {
Instant inst = Instant.parse("2017-02-03T10:37:30.00Z");
System.out.println(inst);
}
}
输出:
Java Instant示例: now()
import java.time.Instant;
public class InstantExample2 {
public static void main(String[] args) {
Instant instant = Instant.now();
System.out.println(instant);
}
}
输出:
Java即时示例: minus()
import java.time.*;
public class InstantExample3 {
public static void main(String[] args) {
Instant instant = Instant.parse("2017-02-03T11:25:30.00Z");
instant = instant.minus(Duration.ofDays(125));
System.out.println(instant);
}
}
输出:
Java即时示例: plus()
import java.time.*;
public class InstantExample4 {
public static void main(String[] args) {
Instant inst1 = Instant.parse("2017-02-03T11:25:30.00Z");
Instant inst2 = inst1.plus(Duration.ofDays(125));
System.out.println(inst2);
}
}
输出:
Java即时示例: isSupported()
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class InstantExample5 {
public static void main(String[] args) {
Instant inst = Instant.parse("2017-02-03T11:35:30.00Z");
System.out.println(inst.isSupported(ChronoUnit.DAYS));
System.out.println(inst.isSupported(ChronoUnit.YEARS));
}
}
输出: