Java 實(shí)例/持續(xù)時(shí)間

2018-03-12 13:37 更新

Java日期時(shí)間 - Java實(shí)例/持續(xù)時(shí)間


實(shí)例和持續(xù)時(shí)間允許我們記錄時(shí)間戳和已用時(shí)間。

我們可以從瞬間添加和減去持續(xù)時(shí)間,以獲得另一個(gè)瞬間。

通過添加兩個(gè)持續(xù)時(shí)間,我們可以獲得另一個(gè)持續(xù)時(shí)間。

即時(shí)和持續(xù)時(shí)間類別分別存儲(chǔ)秒和納秒。

即時(shí)和持續(xù)時(shí)間更常使用機(jī)器級(jí)時(shí)間。

實(shí)例

瞬間表示獨(dú)特的時(shí)刻。

一個(gè)時(shí)代是用作測(cè)量其他時(shí)刻的起源的瞬間。 時(shí)代是在1970-01-01T00:00:00Z。

兩個(gè)連續(xù)時(shí)刻之間的時(shí)間是1納秒。

時(shí)代之后的時(shí)刻具有正值,而時(shí)代之前的時(shí)刻具有負(fù)值。

在時(shí)期的瞬間被分配零值。

我們可以使用Instant.now()來獲取使用系統(tǒng)默認(rèn)時(shí)鐘的當(dāng)前時(shí)刻。

import java.time.Instant;

public class Main {
  public static void main(String[] args) {
    Instant instantNow = Instant.now();
    System.out.println(instantNow);
  }
}

上面的代碼生成以下結(jié)果。



例2

您可以從歷元偏移創(chuàng)建即時(shí)。

以下代碼創(chuàng)建一個(gè)Instant對(duì)象以表示從時(shí)代開始的9秒。

import java.time.Instant;

public class Main {
  public static void main(String[] args) {
    Instant instance9 = Instant.ofEpochSecond(9);
    System.out.println(instance9);
    
    instance9 = Instant.ofEpochSecond(-9);
    System.out.println(instance9);
  }
}

上面的代碼生成以下結(jié)果。


注意

兩個(gè)時(shí)刻可以比較知道是否發(fā)生在其他之前或之后。

實(shí)例和持續(xù)時(shí)間用于記錄兩個(gè)事件之間的時(shí)間戳和經(jīng)過時(shí)間。

持續(xù)時(shí)間

Duration 對(duì)象表示兩個(gè)時(shí)刻之間的時(shí)間跨度。

Duration類可以具有正值和負(fù)值。

我們可以使用它的一個(gè)XXXX()靜態(tài)工廠方法創(chuàng)建Duration類。

import java.time.Duration;

public class Main {
  public static void main(String[] args) {

    Duration d1  = Duration.ofDays(2);
    System.out.println(d1);

    Duration d2  = Duration.ofMinutes(2);
    System.out.println(d2);

  }
}

上面的代碼生成以下結(jié)果。

例3

乘法,除法和否定適用于Duration對(duì)象。

import java.time.Duration;

public class Main {
  public static void main(String[] args) {
    Duration d  = Duration.ofSeconds(200); // 3 minutes and 20 seconds 
    Duration d1  = d.multipliedBy(2);   // 6  minutes and  40  seconds 
    Duration d2  = d.negated();            // -3  minutes and  -20  seconds
    System.out.println(d);
    System.out.println(d1);
    System.out.println(d2);
  }
}

上面的代碼生成以下結(jié)果。

例4

以下代碼顯示了如何從Instant中獲取秒和納秒:

import java.time.Instant;

public class Main {
  public static void main(String[] args) {
    Instant i1 = Instant.now();
   
    long seconds = i1.getEpochSecond();
    System.out.println(seconds);
    int nanoSeconds = i1.getNano();
    System.out.println(nanoSeconds);
  }
}

上面的代碼生成以下結(jié)果。

例5

以下代碼顯示了如何進(jìn)行即時(shí)和持續(xù)時(shí)間計(jì)算。

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

public class Main {
  public static void main(String[] args) {
    Duration d1 = Duration.ofSeconds(55);
    Duration d2 = Duration.ofSeconds(-17);
    
    Instant i1 = Instant.now();
    
    Instant i4 = i1.plus(d1);
    Instant i5 = i1.minus(d2);

    Duration d3 = d1.plus(d2);
    System.out.println(d3);
  }
}

上面的代碼生成以下結(jié)果。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)