當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java LocalDate toEpochSecond()用法及代碼示例


LocalDate類的toEpochSecond()方法用於將此LocalDate轉換為自1970-01-01T00:00:00Z以來的秒數。該方法將此本地日期與指定的時間和作為參數傳遞的偏移量相結合,以計算epoch-second值,該值是從1970-01-01T00:00:00Z開始經過的秒數。時期之後的時間軸上的瞬間為正,早期為負。

用法:

public long toEpochSecond(LocalTime time,
                          ZoneOffset offset)

參數:此方法接受兩個參數time和offset,它們是本地時間和區域偏移。


返回值:此方法返回long,它是自1970-01-01T00:00:00Z的紀元以來的秒數,可能為負數。

以下示例程序旨在說明toEpochSecond()方法:

示例1:

// Java program to demonstrate 
// LocalDate.toEpochSecond() method 
  
import java.time.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a LocalDate object 
        LocalDate localD 
            = LocalDate.parse("2018-12-06"); 
  
        // print LocalDate 
        System.out.println("LocalDate: "
                           + localD); 
  
        // create a LocalTime object 
        LocalTime time 
            = LocalTime.parse("20:12:32"); 
  
        // print Instant 
        System.out.println("Passed LocalTime: "
                           + time); 
  
        // create ZoneId 
        ZoneOffset zone = ZoneOffset.of("Z"); 
  
        // print ZoneId 
        System.out.println("Passed ZoneOffset: "
                           + zone); 
  
        // print result 
        System.out.println("Epoch Second: "
                           + localD.toEpochSecond(time, zone)); 
    } 
}

輸出:

LocalDate: 2018-12-06
Passed LocalTime: 20:12:32
Passed ZoneOffset: Z
Epoch Second: 1544127152

示例2:

// Java program to demonstrate 
// LocalDate.toEpochSecond() method 
  
import java.time.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a LocalDate object 
        LocalDate localD 
            = LocalDate.parse("2019-01-01"); 
  
        // print LocalDate 
        System.out.println("LocalDate: "
                           + localD); 
  
        // create a LocalTime object 
        LocalTime time 
            = LocalTime.parse("00:00:00"); 
  
        // print Instant 
        System.out.println("Passed LocalTime: "
                           + time); 
  
        // create ZoneId 
        ZoneOffset zone = ZoneOffset.of("Z"); 
  
        // print ZoneId 
        System.out.println("Passed ZoneOffset: "
                           + zone); 
  
        // print result 
        System.out.println("Epoch Second: "
                           + localD.toEpochSecond(time, zone)); 
    } 
}

輸出:

LocalDate: 2019-01-01
Passed LocalTime: 00:00
Passed ZoneOffset: Z
Epoch Second: 1546300800

參考: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#toEpochSecond(java.time.LocalTime, java.time.ZoneOffset)



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 LocalDate toEpochSecond() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。