java8 - java.time.instant类教程与实例

2,378 阅读4分钟

Java8 java.time.instant Class example

在本教程中,你将了解到java.time.Instant的例子以及如何在java 8中转换为不同的时间和日期类。

什么是java中的instant?

instant 是一个定义在java.time包中的类。

它在时间轴中代表datetime ,具有正确的nanoseconds 的精度。而Java.util.Date 以毫秒的精度表示日期和时间。

Instant 储存纳秒,所以它需要更多的存储空间,因为它储存的数字比长的大。在内部,它被存储在两个字段中。作为Instant初始化的一部分,构造函数也需要两个字段:Instant(long epochSecond, int Nanos)

  • 长的epochSecond值。从标准历时开始的秒数
  • 整数Nanos值。从最后一秒开始的纳秒数。这个值在0到999,999,999之间。

它存储了更大的长值,而Java.util.Date 则存储了自震旦时间以来的许多毫秒的长值。

即时类的例子

下面是即时类对象的层次结构

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

instant类是不可改变的,并且是线程安全的。

instant 即时类给出了纳秒级精度的时间,而Date给出了毫秒级精度。

instant比Date更精确。我们需要学习如何在java8中把instant转换为Datefrom() 是定义在java.util.Date 类中的一个静态方法,用于从java.time.instant转换为Date对象。

import java.time.Instant;
import java.util.Date;

public class ConvertInstantToDate {
    public static void main(String[] args) {
        Instant instant=Instant.now();
        Date date = Date.from(instant);
        System.out.println(instant);
        System.out.println(date);
    }
}

输出:

2018-08-27T16:04:13.627331100Z  
Mon Aug 27 21:34:13 IST 2018  

Instant 是java8中引入的一个新类。在有些情况下,我们需要从 转换到 。 类不支持纳秒。Date Instant Date

import java.time.Instant;
import java.util.Date;

public class ConvertDateToInstant {
    public static void main(String[] args) {
        Date date = new Date();
        System.out.println(date);
        Instant instant = date.toInstant();
        System.out.println(instant);
    }
}

输出:

Mon Aug 27 21:39:35 IST 2018  
2018-08-27T16:09:35.429Z  

instant 类将无法使用人类可读的年、月、日单位进行平等检查。为了使平等性工作,你需要首先转换为LocalDateLocalDateTimeZonedDateTime ,并使用即时时区。

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;

public class InstantEqualCheck {
    public static void main(String[] args) {
        Instant instantTime1 = Instant.now();
        Instant instantTime2 = Instant.now().plus(5, ChronoUnit.HOURS);
        Instant instantTime3 = Instant.now().plus(5, ChronoUnit.HOURS);
        LocalDate ld1 = LocalDateTime.ofInstant(instantTime1, ZoneId.systemDefault()).toLocalDate();
        LocalDate ld2 = LocalDateTime.ofInstant(instantTime2, ZoneId.systemDefault()).toLocalDate();
        LocalDate ld3 = LocalDateTime.ofInstant(instantTime3, ZoneId.systemDefault()).toLocalDate();
        System.out.println(ld1.isEqual(ld2));
        System.out.println(ld2.isEqual(ld3));
    }
}

输出:

false  
true  

LocalDateTime 类持有 , 和 信息。通过传递 信息和 ,使用 方法创建 对象。Date time Timezone Zone LocalDateTime ZonedDateTime.of() Instant

import java.time.*;
import java.util.TimeZone;

public class ConvertLocalDateTimeToInstant {
    public static void main(String[] args) {
        LocalDateTime localDateTime = LocalDateTime.of(2021, Month.AUGUST, 25, 13, 39);
        Instant instant= ZonedDateTime.of(localDateTime, TimeZone.getTimeZone("EST").toZoneId()).toInstant();
        System.out.println(instant);
    }
}

输出:

2018-08-25T18:39:00Z  

LocalTime 是一个以ISO-8601格式表示没有时区的时间的类。 LocalTimeInstant 是为了不同的目的而引入的。

import java.time.Instant;
import java.time.LocalTime;
import java.time.ZoneId;

public class ConvertInstantToLocalTime {
    public static void main(String[] args) {
        Instant instant = Instant.now();
        LocalTime local =  LocalTime.from(instant.atZone(ZoneId.of("GMT+3")));
        System.out.println(instant);
        System.out.println(local);
    }
}

输出:

2018-08-27T16:30:35.123741700Z  
19:30:35.123741700  

如何在java8中把瞬间转换为一个字符串对象?

DateTimeFormatter 对象是用format 和默认的 timezone 创建的。调用format() 方法来转换为字符串。

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class ConvertInstantToString {
    public static void main(String[] args) {
        Instant instant = Instant.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_INSTANT
                .withZone(ZoneId.systemDefault());
        DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                .withZone(ZoneId.systemDefault());
        DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("MMM dd,yyyy HH:mm:ss")
                .withZone(ZoneId.systemDefault());
        System.out.println(instant);
        System.out.println(dateTimeFormatter.format(instant));
        System.out.println(dateTimeFormatter1.format(instant));
        System.out.println(dateTimeFormatter2.format(instant));
    }
}

输出:

 2018-08-27T16:42:35.853060600Z  
2018-08-27T16:42:35.853060600Z  
2018-08-27 22:12:35  
Aug 27,2018 22:12:35

如何在java8中添加或减去天、小时、秒的即时对象?

minus()方法用于在增加一个特定的时间后返回一个新的实例,减去一个特定的时间后返回一个新实例。

import java.time.Duration;
import java.time.Instant;

public class AddSubtractHoursToInstant {
    public static void main(String[] args) {
        Instant instant = Instant.now();
        System.out.println(instant);
        System.out.println("Add One Day " + instant.plus(Duration.ofDays(1)));
        System.out.println("Add 5 hours " + instant.plus(Duration.ofHours(5)));
        System.out.println("Add 50 minutes" + instant.plus(Duration.ofMinutes(50)));
        System.out.println("Subtract One Day " + instant.minus(Duration.ofDays(1)));
        System.out.println("Subtract 5 hours " + instant.minus(Duration.ofHours(5)));
        System.out.println("Substrat 50 minutes" + instant.minus(Duration.ofMinutes(50)));
    }
}

输出:

 2018-08-27T16:51:59.328782200Z  
Add One Day 2018-08-28T16:51:59.328782200Z  
Add 5 hours 2018-08-27T21:51:59.328782200Z  
Add 50 minutes2018-08-27T17:41:59.328782200Z  
Subtract One Day 2018-08-26T16:51:59.328782200Z  
Subtract 5 hours 2018-08-27T11:51:59.328782200Z  
Substrat 50 minutes2018-08-27T16:01:59.328782200Z

即时isSupported()方法示例

isSupported() 方法检查该字段是否被支持。

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class InstantSupportedExample {
    public static void main(String[] args) {
        Instant instant = Instant.now();
        System.out.println(instant);
        System.out.println(instant.isSupported(ChronoUnit.DAYS));
        System.out.println(instant.isSupported(ChronoUnit.YEARS));
        System.out.println(instant.isSupported(ChronoUnit.WEEKS));
    }
}

输出:

2018-08-27T16:57:13.606815900Z  
true  
false  
false  

总结

最后,在本教程中,你学到了java.time.Instant类在java8中的应用以及使用该类的多个例子